Force Eager Initialization of Static Variables in Dynamically Linked Libs

こ雲淡風輕ζ 提交于 2019-12-11 03:57:42

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!