问题
The C++11 Standard states, § 3.6.2, 4:
"It is implementation-defined whether the dynamic initialization of a non-local variable with static storage duration is done before the first statement of main."
The C++ Standard distinguishes static initializations, which requires only evaluation of compile time constants, from dynamic initialization. I believe the observable effects of eager static initialization are guaranteed. I'm interested in eager initialization in any case.
Given that this behavior is implementation defined and given existing implementations, is there a good portable way to force eager initialization? Is this a decision made by the compiler or linker? I think dlopen() with RTLD_NOW gives this behavior so I suspect this is possible and that it's a linker option.
To be concrete, I want to dynamically link libraries and have constructors for the globals run before main().
An example of a possible usage can be found in this question:
C++ global variable not initialized when linked through static libraries, but OK when compiled with source
The idea is to have some global registry of classes that is accessed within the main function and that classes in dynamically linked libraries can add themselves to by initializing a static variable. That static variable grabs ahold of the global registry and adds something to it. This works sometimes but is unreliable and unpredictable because it depends on undefined behavior.
来源:https://stackoverflow.com/questions/24917581/force-eager-initialization-of-static-variables-in-dynamically-linked-libs