Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

global variables in C++

In a C++ multi-threaded application with many classes, i am trying to find out what are the methods to define a global variable

  1. C style, define it as global in any one source file, define it as extern in a header which is included in the classes that access this variable.

  2. Write a Singleton class, which contains these global variables and exposes set/get methods to write to the variable.

By second method one can control multi-threaded access via locks in a centralized manner rather than the first approach.

Are there more and better ways?

like image 410
Sashi Avatar asked Aug 25 '10 16:08

Sashi


1 Answers

First of all try to avoid global variables as much as you can. If you just need to do it (by example this is the case with cin, cout and cerr) your second method is definitely the best (and more natural) way of doing it.

like image 199
Dacav Avatar answered Oct 26 '22 02:10

Dacav