C ++链接器问题 [英] C++ linker issues
问题描述
a.cpp
int localfunction(){return 1; }
int local_symbol = localfunction();
b.cpp
void thirdfunction(){};
main.cpp
void main(){thirdfunction();当我在一个主要的可执行文件中编译这个时,一切都有效(即使有优化),而localfunction是在启动时执行,即使我不直接调用它。
现在,在Visual C ++和GCC中,我将a.cpp和b.cpp放在静态库(.lib)中。 localfunction不再执行/定义。
根据我的理解,符号被检测为未使用,并被删除。但它听起来很奇怪,因为:
- 为什么当我不使用.lib文件
$ b
<
$ b
我想要做的是在每个.lib文件中有一组启动函数,我使用该寄存器自动注册一些数据。主要可执行文件不应该知道什么文件被链接,也不明确引用localfunction(/ INCLUDE确实有效,但它不是最佳的)
BTW:使用各种VC ++选项(OPT:NOREF等)没有解决问题。
谢谢!
QbProg
解决方案静态库基本上是一个库或目录文件
当链接器在构建应用程序时使用静态库来解析依赖关系时,它会遵循在库中寻找帮助它解析的对象文件的过程程序中任何未定义的符号。
在您的实例中,从 main.cpp $生成的对象文件c $ c>是指 third_function()
。可以通过链接从 b.cpp
生成的对象文件来解决此依赖关系。这个目标文件不再引入未定义的符号,所以链接器可以(而且确实)在这里停止。
为了最大的可移植性 main 应该返回 int
。
a.cpp
int localfunction () { return 1; }
int local_symbol = localfunction();
b.cpp
void thirdfunction () {};
main.cpp
void main () { thirdfunction (); }
When I compile this in a main executable everything works (even with optimizations), and the localfunction is executed at startup even if I don't call it directly.
Now, in Visual C++ and GCC , I put a.cpp and b.cpp in a static library (.lib). localfunction is no more executed/defined.
From what I understand the symbol is detected as "not used" and it is removed. But it sounds weird because:
- Why it is not removed when I don't use the .lib file?
- Since the lib is linked in, why the linker blows away the initialization code?
What I'm trying to do to is to have a set of startup function in every .lib file I use that register automatically some data. The main executable should not know what files are linked in nor explicitly reference "localfunction" (/INCLUDE does works but it is not optimal)
BTW : using the various VC++ options (OPT:NOREF , etc..) doesn't solve the problem.
Thank you!
QbProg
解决方案 A static library is - basically - an library, or archive, of object files compiled from that library's constituent source files.
When the linker uses a static library to resolve dependencies while building an application, it follows a process of looking for object files in the library that help it resolve any undefined symbols in the program. It doesn't automatically include all of the object files in a library.
In your instance the object file generated from main.cpp
refers to third_function()
. This dependency can be resolved by linking in the object file generated from b.cpp
. This object file introduces no further undefined symbols, so the linker can (and does) stop here.
Oh, and for maximum portability main
should return int
.
这篇关于C ++链接器问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!