问题描述
我遇到以下问题:我的(C ++-)项目由几个子项目组成.在每个文件中,我都有几个文件,这些文件带有要在启动时运行的代码.到目前为止,我的解决方案是使用静态变量在初始化时调用相应的代码,如下所示:
I have the following problem: My (C++-)project consists of several subprojects. In each, I have several files with code I want to run at startup. My solution so far is to use static variables which call the respective code on initialization like this:
// Foo.cpp
static TFooRegistry sFooRegistry; // does stuff in constructor.
在每个子项目中使用dll构建我的项目时,一切正常,代码按预期运行.但是,当静态链接子项目时,链接器确定Foo.o不包含任何从外部引用的代码,并对其进行优化.当然,我可以在其他地方添加对sFooRegistry的引用,但这很乏味且容易出错.
When building my project using dlls for each subproject, everything works fine and the code runs as expected. When linking the subprojects statically, however, the linker determines that Foo.o contains no code ever referenced from outside and optimizes it away. Of course I could add a reference to sFooRegistry somewhere else, but this is tedious and error prone.
有哪些解决方法(符合标准的标准)?
What (standard conformant) ways of solving this are there?
好的,在Mac/GCC和Win/Visual Studio上我该怎么办?
OK, what can I do on mac/gcc and win/visual studio?
推荐答案
尚无标准的强制初始化库中对象的标准方法-您必须根据自己的特定平台使用技巧. DLL和静态库(至少在Windows上)之间的区别在于:前者具有由操作系统执行的启动和关闭代码,而后者只是目标文件的串联.
There are no standard conformant ways of forcing objects in libraries to be initialised - you have to use tricks depending on your particular platform(s). The difference between a DLL and and a static library (on Windows, at least) is that theformer has start-up and shut-down code that is executed by the OS, whereas the latter is just a concatenation of object files.
此外,链接器也没有优化您的启动代码-它只是没有链接它,因为它显然从未使用过.连结子是非常愚蠢的野兽-如果您想了解它们的行为,请看一看在链接器&加载程序.
Also, the linker is not optimising away your start up code - it is simply not linking it, because it apparently is never used. Linkersare pretty stupid beasts - if you want to find out how they do what they do, take a lookat the book Linkers & Loaders.
这篇关于如何防止链接器优化启动代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!