I would like to setup in a library a global variable like “gMyClass” pointing to MyClass and make sure this variable is in the global scope of my program when MyClass.h is included.
Is there any instruction to do so ?
Looking at TSystem, it looks like this might be related to R__EXTERNTSystem *gSystem;
I think, maybe @bellenot can correct me, R__EXTERN is needed for Windows to define variables in a global scope. If you are not using Windows, you can just define the variables globally.
To make sure that we are giving the best advice, let me ask you why you need this global variable (using global variable is usually a complication for many coding patterns including but not limited to using multiple threads).
Hi @pcanal, thank you for asking.
I basically have a singleton class that I want to expose to the end user through a library and I don’t want him to either declare or destruct it by himself.
global variable, ROOT style is a good convention so I would like to reproduce but at the level of my library
I am also interested about the way ROOT is handling multithreading in that case. I think gSystem is properly working through multiple threads. I guess this might actually different instances, is it?
gROOT: a real singleton. Routine have to be internally locks to avoid conflicts when they touch anything after initialization. Initialization is “guaranteed” via gROOT being a macro that expand to a function that does the initialization.
gSystem : a real singleton. Routine have to be internally locks to avoid conflicts when they touch anything after initialization. Initialization is “guaranteed” to be there before multi-thread supported is started (by a user call to ROOT::EnableThreadSafety()) thanks to gROOT being initialized first.
gDirectory : a thread local static implemented via a complex trampoline setup.
Global variable have an issue with order of initialization and thus we actually rely more on function static.
If you singleton class is also const then the simplest solution is: