user1701840
user1701840

Reputation: 1112

How to use nested namespace in different files?

//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

Answers (2)

greatwolf
greatwolf

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:

  • 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()
{
  // ...
}

Upvotes: 1

Jay
Jay

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

Related Questions