namespace

Started by
6 comments, last by janta 16 years, 2 months ago
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?
Advertisement
Required reading.

Namespaces.
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 1int globalVar;// .cpp 2extern int globalVar;globalVar++;


Or with functions:

// .cpp 1int globalVarvoid IncrementVar(){    globalVar++;}// .cpp 2extern void IncrementVar(); // extern is implicit, usually nobody writes it explicitlyIncrementVar(); 


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.
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.
Hey thanks everybody I'm gonna do some more reading I think I get it.

I use global variables because global variables kick ass.
Quote:I use global variables because global variables kick ass.
No. Just the opposite.
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.
Begining of your project: global variables kick ass
End of you project: they get you ass kicked.

[grin]

This topic is closed to new replies.

Advertisement