Sign in to follow this  
icecubeflower

namespace

Recommended Posts

Hey what if you use global variables but then your .cpp file is getting unmanageable and you want to split it into several .cpp and .h files? I still want them all to use the same global variables. Is that possible? Would you use a namespace? What's a namespace?

Share this post


Link to post
Share on other sites
uuugghh global variables [smile]
In order to access a variable defined in a compilation unit (a cpp file) from another compilation unit, you will need an "extern" somewhere. Either:


// .cpp 1
int globalVar;

// .cpp 2
extern int globalVar;
globalVar++;


Or with functions:


// .cpp 1
int globalVar
void IncrementVar()
{
globalVar++;
}

// .cpp 2
extern void IncrementVar(); // extern is implicit, usually nobody writes it explicitly

IncrementVar();


Throw in a few classes and replace global variables by dynamically allocated objects (or have a container handle that for you) and your code's organization should begin to look a bit more decent.

Share this post


Link to post
Share on other sites
Quote:
Original post by icecubeflower
Hey what if you use global variables but then your .cpp file is getting unmanageable and you want to split it into several .cpp and .h files? I still want them all to use the same global variables. Is that possible? Would you use a namespace? What's a namespace?


In addition to what others said:

The global variables likely are a big part of why the .cpp file is "getting unmanageable". Could we see the code? I want to get a sense of what you're using them for and why you think you need as many of them as you do.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this