Archived

This topic is now archived and is closed to further replies.

variables in namespaces

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

If you intended to correct an error in the post then please contact us.

Recommended Posts

hums, trying to get variables within namespaces to work. at first i got an error about already defined when simply putting a variable within the namespace, so i made it static wich seemekd to work until now. if i try to access the variable from anywhere else but from within the namespace it decides to just ignore it ie. not alter it, would anyone care to shed some light over this? thanks in advance oh using gcc 3.2(mingw) btw. - Damage Incorporated. [edited by - damage_incorporated on October 15, 2003 11:22:26 AM]

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
You have to refer to the variable inside the namespace like it was in a class, like this:

theNamespace::theObjectYouWantToAccess

You can also make all the objects in the namespace global by putting this in the source file you are working on:

using namespace yourNamespaceHere;

but this sort of defeats the purpose of a namespace...

You can also get rid of the clumsy syntax by doing this:

using theNamespace::theObjectYouWantToAccess;

This makes only the object you want to access in the namespace global to all members. Do this if you want to access the object a lot. If you are going to access it only a few times, use the first way.

Share this post


Link to post
Share on other sites
foo.hpp

namespace foo {

// ...


extern int bar;

// ...

}

foo.cpp

#include "foo.hpp"

int foo::bar = 0; // initialise to whatever you want


And a file that includes foo.hpp (and is linked with foo.cpp):

// ...


void pie() {
std::cout << "originally, foo::bar = " << foo::bar << std::endl;
foo::bar = 42;
std::cout << "now, foo::bar = " << foo::bar << std::endl;

// ...

}

// ...


I assume from your post ("... decides to just ignore it ie. not alter it") that you wanted a non-const variable. Anyway, here is an example of a constant definition, just in case you meant otherwise:

bar.hpp

namespace bar {

// ...


const int universe = 42;

// ...

}


[ Google || Start Here || ACCU || STL || Boost || MSDN || GotW || CUJ || MSVC++ Library Fixes || BarrysWorld || E-Mail Me ]

[edited by - Lektrix on October 15, 2003 12:15:14 PM]

Share this post


Link to post
Share on other sites