Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the best way to use global variables in c++?

Tags:

c++

For me, I usually make a global class with all members static. All other classes will inherit from this global class.

I wonder if this is a good practice?

Anybody got any suggestions?


2 Answers

Generally try to avoid global variables as they introduce global state. And with global state you do not have referential transparency. Referential transparency is a good thing and global state is a bad thing. Global state makes unit tests pretty pointless for example.

When you have to though, I'd agree that most of the time the method you mentioned is fine. You can also declare the global variable in any .cpp file and then have in your .h file an extern to that global variable.

like image 134
Brian R. Bondy Avatar answered Oct 28 '25 22:10

Brian R. Bondy


Best way? Carefully... :-)

like image 29
Chris J Avatar answered Oct 28 '25 23:10

Chris J



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!