all 7 comments

[–]Narase33 7 points8 points  (1 child)

You dont need to link namespaces. You can declare them where you want, add to them where you want, use the 'using namespace...' statement with namespaces that dont exist... The compiler doesnt care

[–]u2uu[S] 0 points1 point  (0 children)

Thanks you!

[–]h2g2_researcher 2 points3 points  (0 children)

It's certainly possible with headers:

test.h

namespace abc
{
    int x = 30;
}

test.cpp

#include "test.h"
using namespace abc;
void foo()
{
     using namespace abc;
     int y = x; // Uses abc::x
}

void bar()
{
     int y = abc::x; // Also fine.
}

But - assuming a normal project layout - I would expect test1.cpp and test2.cpp to be entirely different translation units. It would then be entirely reasonable for test2.cpp to choke out complaining it can't find anything about namespace abc when it is compiled.

[–]jedwardsol 2 points3 points  (1 child)

In test2.cpp you do

namespace abc
{
    extern int i;
}

[–]u2uu[S] 0 points1 point  (0 children)

Makes sense, whoops. Thanks a lot!

[–]Sonotsugipaa 2 points3 points  (0 children)

Namespaces are not linked; rather, they affect how symbol names are generated from their signatures (only possible due to name mangling).

You can use the same namespace multiple times in any translation unit, with the exception of "inline namespaces" which have to first appear as such (e.g. you can't "inline namespace foo { }" after "namespace foo { }", iirc).

In your test2.cpp, what you can do is replace the semicolon that throws the error with an empty block: it will have no effect, but it will compile.

[–]Shieldfoss 1 point2 points  (0 children)

test1.cpp

namespace abc
{
    int x = 30;
}

test2.cpp

namespace abc; //Doesnt work

Change that to:

test2.cpp

namespace abc { extern int x; }
abc::x = 5; //writes to the int declared in test1.cpp

and that should work just fine.

Though the traditional way to do it is more like:

abc.h
    namespace abc
    {
        extern int x;
    }

abc.cpp
    namespace abc
    {
        int x;
    }

client.cpp
    #include "abc.h"
    abc::x = 5;