R__EXTERN like variable

Hello,

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__EXTERN TSystem *gSystem;

Thank you.

Hi,

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.

Lorenzo

Hi Lorenzo,

Ok, R__EXTERN is maybe not what I need. May I ask how ROOT is handling gSystem variable ? In terms of constructor and destructor calls ?

I would like to achieve the same at the loading stage of my library with MyClass object.

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?

We have different handling for different case.

  • 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:

SingletonClass & GetSingletonObject() 
{
    static SingletonClass static_object(....);
    return static_object;
}

where the initialization is guaranteed (as-is) to be thread-safe and done in time (i.e. when the user actually uses it first) by the C++ standard

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.