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:
- file.h declares a
foo existing in namespace first::second.
- file.c brings namespace
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.
- main.c brings namespace
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().
- you get a linking error for unresolved symbol because
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()
{
// ...
}
using namespacewill affect function calls, but not definitions. Your definition offoois in the global namespace.