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

China☆狼群 提交于 2020-01-10 20:22:07

问题


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

statinit.cpp has some static initializations that I need running. However, I never explicitly reference anything from statinit.cpp in my main(), or in anything referenced by it. What happens (I suppose) is that the linked object created from statinit.cpp is never loaded on runtime, so my static initializations are never run, causing a problem elsewhere in the code (that was very difficult to debug, but I traced it eventually).

Is there a standard library function, linker option, compiler option, or something that can let me force that object to load on runtime without referencing one of its elements?

What I thought to do is to define a dummy function in statinit.cpp, declare it in a header file that main() sees, and call that dummy function from main(). However, this is a very ugly solution and I'd very much like to avoid making changes in statinit.cpp itself.

Thanks, Daniel


回答1:


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.



回答2:


I ran into the same problem.

Write a file, DoNotOptimizeAway.cpp:

void NoDeadcodeElimination()
{
    // Here use at least once each of the variables that you'll need.
}

Then call NoDeadcodeElimination() from main.

EDIT: alternatively you can edit your linker options and tell it to always link everything, even if it's not used. I don't like this approach though since executables will get much bigger.




回答3:


These problems, and the problems with these potential solutions all revolve around the fact that you can't guarantee much about static initialization. So since it's not dependable, don't depend on it!

Explicitly initialize data with a static "InititalizeLibrary" type static function. Now you guarantee it happens, and you guarantee when it happens in relation to other code based on when you make the call.




回答4:


One C++'ish way to do this is with Singletons.

Essentially, write a function to return a reference to the object. To force it to initialize, make it a static object inside the function.

Make a class static function that is vaguely like this:

class MyClass {
   static MyClass& getObject()
   {
        static MyObject obj;
        return obj;
    }
};



回答5:


Since you are using C++, you could always declare a global object (ie a global variable that references a class in statinit.cpp. As always, the constructor will be called on initialization and since the object is global, this will be called before main() is run.

There is one very important caveat though. There is no guarantee as to when the constructor will be called and there is no way to explicitly order when each of these constructors is called. This will also probably defeat any attempt to check for memory leaks since you can no longer guarantee that all the memory allocated while running main has been deallocated.




回答6:


Is the problem that the static items were never initialized, or is the problem that the static items weren't initialized when you needed to use them?

All static initialization is supposed to be finished before your main() runs. However, you can run into issues if you initialize on static object with another static object. (Note: this doesn't apply if you are using primitives such as int)

For example, if you have in file x.cpp:

static myClass x(someVals);

And in y.cpp:

static myClass y = x * 2; 

It's possible that the system will try to instantiate y before x is created. In that case, the "y" variable will likely be 0, as x is likely 0 before it is initialized.

In general, the best solution for this is to instantiate the object when it is first used (if possible). However, I noticed above you weren't allowed to modify that file. Are the values from that file being used elsewhere, and maybe you can change how those values are accessed?




回答7:


Read the manual page for the ld command and look at the -u option. If statinit.cpp defines anything that looks like a function then try naming it in -u. Otherwise choose a data object that's defined in statinit.cpp and name that in -u, and hope it works. I think it's best if you write the command line so the -u option comes immediately before your -l option for your library that has statinit's object code in it.




回答8:


Of course the dynamic library solution is the best, but I've also been told it's possible to link the whole static library with the linker option:

-Wl,-whole-archive

before the library's -l option, and

-Wl,-no-whole-archive

after it (to avoid including other libraries as a whole, too).



来源:https://stackoverflow.com/questions/1939899/how-do-i-make-an-unreferenced-object-load-in-c

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