Search code examples
c++static-initialization

dynamic initialisation of global statics, races and timing


Is it guarantied that global statics are (dynamically) initialised before e.g. main() is called resp. LoadLibrary()/dlopen() returns? Or is it possible that they get "lazy" initialised - just before any function in the specific translation unit is called?

Second question, is the initialisation always serial, even over multiple translation units, or races could occur?


Solution

  • From Deferred_dynamic_initialization

    It is implementation-defined whether dynamic initialization happens-before the first statement of the main function (for statics) or the initial function of the thread (for thread-locals), or deferred to happen after.

    So it is not guarantied that global statics are (dynamically) initialised before main() generally. You have to see with your compiler documentation for more guaranty.