如何防止链接器优化启动代码?
我有以下问题:我的(C++-)项目由多个子项目组成。 在每个文件中,我都有几个文件,其中包含我想要在启动时运行的代码。 到目前为止,我的解决方案是使用静态变量,它们在初始化时调用相应的代码,如下所示:
// Foo.cpp
static TFooRegistry sFooRegistry; // does stuff in constructor.
当使用每个子项目的 dll 构建我的项目时,一切正常并且代码按预期运行。 然而,当静态链接子项目时,链接器确定 Foo.o 不包含从外部引用的代码,并将其优化掉。 当然,我可以在其他地方添加对 sFooRegistry 的引用,但这很乏味且容易出错。
有哪些(符合标准的)方法可以解决这个问题?
好的,我可以在 mac/gcc 和 win/visual studio 上做什么?
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.
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?
OK, what can I do on mac/gcc and win/visual studio?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
没有标准的一致方法可以强制初始化库中的对象 - 您必须根据您的特定平台使用技巧。 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 the
former 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. Linkers
are pretty stupid beasts - if you want to find out how they do what they do, take a look
at the book Linkers & Loaders.
有些技巧,但回顾一下。
对于 Win 系统(但不是 Linux),请使用显式
dllexport
- 在这种情况下,链接器无法知道外部应用程序是否使用此符号。Some trick, but review it.
For Win system (but not linux) use explicit
dllexport
- in this case linker cannot know if this symbol used by outer app or not.