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

4
  • What compiler do you have? (You may want to try using .h(pp)/.cpp as the extension for source files instead) Commented Jul 19, 2013 at 20:21
  • What about include directives? Commented Jul 19, 2013 at 20:23
  • 1
    You mind adding the actual error message to your question too? (Please don't add it as a comment!) Commented Jul 19, 2013 at 20:23
  • 4
    using namespace will affect function calls, but not definitions. Your definition of foo is in the global namespace. Commented Jul 19, 2013 at 20:25

2 Answers 2

1

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();
}
Sign up to request clarification or add additional context in comments.

1 Comment

I made the change on the file.c according to your answer, and it works!
1

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

1 Comment

WELL EXPLAINED! THANKS!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.