• Advertisement
Sign in to follow this  

namespace

This topic is 3734 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

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
Advertisement
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
Quote:
I use global variables because global variables kick ass.
No. Just the opposite.

Share this post


Link to post
Share on other sites
If I didn't use global variables I would have to pass about 50 variables to most of my functions. The only other thing I can think of would be to throw them all in a struct and pass the struct pointer around.

Share this post


Link to post
Share on other sites
Begining of your project: global variables kick ass
End of you project: they get you ass kicked.

[grin]

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement