Reputation: 1112
//file.h
namespace first
{
namespace second
{
void foo();
}
}
//file.c
using namespace first::second;
void foo()
{
...
}
//main.c
using namespace first::second;
int main()
{
foo();
}
the code above doesn't work as the compiler didn't recognize the foo(). where is my mistake?
Upvotes: 1
Views: 515
Reputation: 20838
I'm going to guess that you got an unresolved linking error when you tried to call foo
from main in the example you posted. There are couple issues at play here starting from the top:
foo
existing in namespace first::second
.first::second
into filescope lookup but it does not affect function definitions. Thus the implementation of void foo() {}
is actually a function defined in global scope -- not in first::second
as you might expect.first::second
into its filescope. The compiler will consider first::second
as well as global scope ::
when you call foo in main. The compiler chooses first::second::foo
since file.h
doesn't declare the global foo()
.first::second::foo
was never implemented.In addition to Jay's suggestion, the other fix you can do is to fully qualify foo's definition similar to member functions:
// file.c
#include "file.h"
void first::second::foo()
{
// ...
}
Upvotes: 1
Reputation: 14471
try this:
This puts the implementation into the namespace
//file.c
namespace first
{
namespace second
{
void foo()
{
...
}
}
}
This tells main explicitly where to find foo:
//main.c
int main()
{
::first::second::foo();
}
Upvotes: 1