如何在C ++中加载未引用的对象? [英] How do I make an unreferenced object load in C++?
问题描述
我有一个.cpp
文件(我们称其为statinit.cpp
)已编译并使用gcc
链接到我的可执行文件中.
我的main()
函数在statinit.cpp
中不是.
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
有一些我需要运行的静态初始化.
但是,我从未在我的main()
中或在它所引用的任何内容中明确引用过来自statinit.cpp
的任何内容.
发生的事情(我想)是从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?
我想做的是在statinit.cpp中定义一个伪函数,在main()
看到的头文件中声明它,然后从main()
调用该伪函数.但是,这是一个非常丑陋的解决方案,我非常想避免对statinit.cpp本身进行更改.
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.
谢谢, 丹尼尔
推荐答案
目前尚不清楚问题所在:
It is not exactly clear what the problem is:
C ++没有静态初始化程序的概念.
因此,假设您在文件范围"中有一个对象.
C++ does not have the concept of static initializers.
So one presume you have an object in "File Scope".
- 如果此对象位于全局名称空间中,则它将在调用main()之前构造,并在main()退出之后(假定它在应用程序中)退出之后销毁.
- 如果此对象位于名称空间中,则可选地,实现可以选择延迟初始化变量.这只是意味着它将在首次使用之前被完全初始化.因此,如果您依赖于构造的副作用,则将对象放在全局名称空间中.
现在,您可能没有看到该对象的构造函数执行的原因是它没有链接到应用程序中.这是一个链接器问题,而不是语言问题.当将对象编译到静态库中,然后将您的应用程序链接到该静态库时,就会发生这种情况.链接器将仅加载到应用程序中明确引用的应用程序功能/对象(即解析符号表中未定义内容的内容).
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.
这篇关于如何在C ++中加载未引用的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!