question about namespaces

Started by
5 comments, last by larspensjo 11 years, 2 months ago

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?

Advertisement
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.
"Most people think, great God will come from the sky, take away everything, and make everybody feel high" - Bob Marley

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

Yup.

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.
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>
"Most people think, great God will come from the sky, take away everything, and make everybody feel high" - Bob Marley

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.

[size=2]Current project: Ephenation.
[size=2]Sharing OpenGL experiences: http://ephenationopengl.blogspot.com/

This topic is closed to new replies.

Advertisement