user2443626
user2443626

Reputation: 93

C++ namespace resolution for inner namespace

Please, explain me why this code results in a linkage error:

xxx.h

namespace ns
{
    namespace inner
    {
        void func();
    }
}

xxx.cpp

using namespace ns;
using namespace inner; //or "using "namespace ns::inner;" results in the same error

void func()
{
}

while this code works fine:

xxx.h

namespace ns
{
    void func();
}

xxx.cpp

using namespace ns;

void func()
{
}

Upvotes: 2

Views: 399

Answers (2)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385098

Short story: using namespace is a nice shortcut for accessing existing declarations, but it does nothing to subsequent ones. (Otherwise they would clearly be entirely ambiguous!)

Upvotes: 1

mukunda
mukunda

Reputation: 2995

using namespace ... only allows names inside that namespace to be referenced without the namespace prefix. Any symbols you define in the source code will still be defined in whichever namespace block they are currently in.

To add a definition of that function, you need to be inside the inner namespace:

// xxx.cpp

using namespace ns::inner;
// we are still outside of the namespace, but we can reference names inside.

namespace ns { namespace inner {
    // now we can define things inside ns::inner
    void func() {

    }
}

// now we are at the global level again.

I'm guessing you didn't get a linker error by moving it to the outer namespace because your code didn't reference it and it was left out of the linking phase.

DISCLAIMER: I don't actually know how using works exactly.

Upvotes: 3

Related Questions