This topic is 1804 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Can you use the same namespace in 2 files? For ex:

test.h

namespace x

{

int i;

};

test2.h

namespace x

{

int u;

};

I guess you have you have to include test.h in test2 right? I just find this kinda peculiar because untill now I never really used namespaces a lot,and it's weird for me to see you can make definitions in the same namespace in different files.

Anyway,am I correct?

##### Share on other sites
Nope, namespaces are "open" in that you can add a name to a namespace in as many different files as you want, and they don't need to include any of the others. All the standard library headers do that.

C# has partial classes which allow you to do the same with a class as well.

##### Share on other sites

wait...so can i add variables and functions to the same namespace from different header files?

Yup.

##### Share on other sites
There is one exception: it's undefined for a C++ program to add to namespace std with a few exceptions like adding specializations for existing library classes.

##### Share on other sites
Downside is you can have headscratching moments whereby you cant add a string as a key on a map even though the compiler knows about a string (forward declaration I guess), but it doesn't know about string::operator< because you didn't #include <string>

##### Share on other sites

This is useful for forward declarations. For example, in you header file, you can do:

namespace XXX {
class YYY;
};


And then you can use declarations with references to XXX::YYY in your header file, without having to include the header file where the real declaration is.