Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use namespace across several files

Tags:

I notice that C++'s std namespace is spread across several files (like in vector, string, iostream, etc.). How can I accomplish the same thing in my programs? Do I simply declare the same namespace in each individual header file, so that it's something like:

a.h

namespace something
{
class A {};
}

b.h

#include "a.h"

namespace something
{
class B : public A {};
}

And then in, say, main.cpp, I would just include "b.h" and "a.h" and then using namespace something; to use the two classes?

like image 420
wrongusername Avatar asked Jan 09 '11 05:01

wrongusername


People also ask

Can you have multiple using namespace?

You can have the same name defined in two different namespaces, but if that is true, then you can only use one of those namespaces at a time. However, this does not mean you cannot use the two namespace in the same program. You can use them each at different times in the same program.

Can I use multiple namespaces in C++?

Namespace is a feature added in C++ and is not present in C. A namespace is a declarative region that provides a scope to the identifiers (names of functions, variables or other user-defined data types) inside it. Multiple namespace blocks with the same name are allowed.

Why do we use namespace in C Plus Plus?

Namespaces are used to organize code into logical groups and to prevent name collisions that can occur especially when your code base includes multiple libraries. All identifiers at namespace scope are visible to one another without qualification.

How do I import a namespace in C++?

Importing a namespace The basic syntax of a namespace import declaration is as follows: using namespace nmspace_name; After such declaration, all names that we would otherwise have referred as nmspace_name::identifier can be used simply as identifier.


1 Answers

Yes, that is exactly how to do it.

like image 141
Andrew Hare Avatar answered Sep 26 '22 07:09

Andrew Hare