static variable initialisation code never gets called

后端 未结 3 874
一整个雨季
一整个雨季 2020-12-21 21:38

I\'ve got an application that\'s using a static library I made. One .cpp file in the library has a static variable declaration, whose ctor calls a function on a singleton th

相关标签:
3条回答
  • 2020-12-21 21:47

    If you have an object in a static library that is not EXPLICITLY used in the application. Then the linker will not pull that object from the lib into the application.

    There is a big difference between static and dynamic libraries.

    Dynamic Library:
    At compile time nothing is pulled from the dynamic library. Extra code is added to explicitly load and resolve the symbols at run-time. At run time the whole library is loaded and thus object initializers are called (though when is implementation detail).

    Static libraries are handled very differently:
    When you link against a static library it pulls all the items that are not defined in application that are defined in the library into the application. This is repeated until there are no more dependencies that the library can resolve. The side effect of this is that objects/functions not explicitly used are not pulled form the library (thus global variables that are not directly accessed will not be pulled).

    0 讨论(0)
  • 2020-12-21 21:53

    Refactor the classes doing static initialization so they do not depend on any other such classes. That is, make each class's initialization independent and self-sufficient.

    0 讨论(0)
  • 2020-12-21 21:57

    My memory of this is a bit hazy, but you might be getting hit with an initialization order problem. There are no guarantees in which order static variable initializers in different files get called, so if your singleton isn't initialized yet when your static variable in the library is being initialized, that might produce the effect you're seeing.

    The way I've gotten around these problems is to have some sort of an explicit init function that does this stuff and that I call at the start of main or something. You might be able to fiddle with the order in which you give the object file and library arguments to the compiler (or linker, actually) because that's also worked for me, but that solution is a bit fragile because it depends not only on using the specific linker but probably also the specific version.

    0 讨论(0)
提交回复
热议问题