How do I make an unreferenced object load in C++?

前端 未结 8 1950
一向
一向 2021-01-03 16:36

I have a .cpp file (let\'s call it statinit.cpp) compiled and linked into my executable using gcc. My main() function is

8条回答
  •  情深已故
    2021-01-03 17:02

    It is not exactly clear what the problem is:

    C++ does not have the concept of static initializers.
    So one presume you have an object in "File Scope".

    • If this object is in the global namespace then it will be constructed before main() is called and destroyed after main() exits (assuming it is in the application).
    • If this object is in a namespace then optionally the implementation can opt to lazy initialize the variable. This just means that it will be fully initialized before first use. So if you are relying on a side affect from construction then put the object in the global namespace.

    Now a reason you may not be seeing the constructor to this object execute is that it was not linked into the application. This is a linker issue and not a language issue. This happens when the object is compiled into a static library and your application is then linked against the static library. The linker will only load into the application functions/objects that are explicitly referenced from the application (ie things that resolve undefined things in the symbol table).

    To solve this problem you have a couple of options.

    • Don't use static libraries.
      • Compile into dynamic libraries (the norm nowadays).
      • Compile all the source directly into the application.
    • Make an explicit reference to the object from within main.

提交回复
热议问题