Followers 0

# including namespace(s)

## 7 posts in this topic

I am looking for the way to use namespaces more efficiently. At this point I use 'glm' and 'std' namespace, and I have found that it cannot be included from one header to the rest like this

base.h

#ifndef _BASE_H_
#define _BASE_H_

...

...
// rest of declarations

...

// namespaces
using namespace glm;
using namespace std;

#endif

app.h

#include "base.h"

// rest of the code goes here

When I do this I get compiler error around namespaces, since I don't like things like 'glm::' and 'std::' in almost every line of code.

Is there a way to use namespaces so they are declared only in one header instead of every header that uses them?

0

##### Share on other sites

You can use individual pieces of the name spaces which can help to eliminate the confliction's.  Like if you are using std::string and glm::whatever, you could...  (May vary based on language, I'm more familiar with C#)

using std::string;

using glm::whatever;

Alternatively you can also "inline include" or scope into a namespace as needed which is the preferred practice I believe.  That is to say...  (Again this varies on your language and is NOT correct syntax.)

using namespace std

{

... stuff here

}

using namespace glm

{

... glm stuff here

}

Personally I believe it's a matter of preference.  I prefer to use individual objects (the first way) many other's prefer to inline scope or whatever you want to call it (the second way).  Anyway, point is compiler errors when using different namespaces probably means that both namespaces define an object with the same name.  So saying to use std and glm (maybe they both have a "string") the compiler doesn't know which "string" you want to use.  Either approach will get past the error, I believe which one you choose should be up to you, I don't know if there is an official standard or any particular difference between the two methods.

0

##### Share on other sites

Its best to be explicit.

Be ye a programmer, or be ye a lazy typist?

2

##### Share on other sites

The documentation of glm explicitly says you should not do a using namespace glm, because there are many short named things inside to make it more like GLSL.

If you really want a using namespace std do it explicitly in a cpp file where you need it, but in a header you should type everything out and not put a using to not give up all usefulness of namespaces, like the others said.

0

##### Share on other sites

In C++ you can also have namespace aliases if you aren't wanting to type really long namespaces.

namespace xyz = Some::Really::Long::Namespace;

xyz::Foo();
2

## Create an account

Register a new account