In a C++ multi-threaded application with many classes, i am trying to find out what are the methods to define a global variable
-
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.
-
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?
If the scope of your “global variable” can be narrowed down (which is typically the case – how many variables are truly global?) then you can make it a private static class member in the appropriate owning class. If your other classes need to see it (or less likely, update it), provide get/put accessors.