简体   繁体   English

静态链接对库实际上做了什么?

[英]What does static linking against a library actually do?

Say I had a library called libfoo which contained a class, a few static variables, possibly something with 'C' linkage, and a few other functions. 假设我有一个名为libfoo的库,它包含一个类,一些静态变量,可能具有“C”链接,还有一些其他函数。

Now I have a main program which looks like this: 现在我有一个主程序,看起来像这样:

int main() {
   return 5+5;
}

When I compile and link this, I link against libfoo . 当我编译并链接它时,我链接libfoo

Will this have any effect? 这会有什么影响吗? Will my executable increase in size? 我的可执行文件会增加吗? If so, why? 如果是这样,为什么? Do the static variables or their addresses get copied into my executable? 静态变量或其地址是否被复制到我的可执行文件中?

Apologies if there is a similar question to this or if I'm being particularly stupid in any way. 如果对此有类似的问题,或者我以任何方式特别愚蠢,请道歉。

It won't do anything in a modern linker, because it knows the executable doesn't actually use libfoo's symbols. 它不会在现代链接器中执行任何操作,因为它知道可执行文件实际上并不使用libfoo的符号。 With gcc 4.4.1 and ld 2.20 on my system: 在我的系统上使用gcc 4.4.1和ld 2.20:

g++ linker_test.cpp -static -liberty -lm -lz -lXp -lXpm -o linker_test_unnecessary
g++ linker_test.cpp -static -o linker_test_none
ls -l linker_test_unnecessary linker_test_none 

They are both 626094 bytes. 它们都是626094字节。 Note this also applies to dynamic linking, though the size they both are is much lower. 请注意,这也适用于动态链接,尽管它们的大小都要低得多。

A library contains previously compiled object code - basically a static library is an archive of .o or .obj files. 库包含以前编译的目标代码 - 基本上静态库是.o或.obj文件的存档。

The linker looks at your object code and sees if there are any unresolved names and if so looks for these in the library, if it finds them it includes the object file that contains them and repeats this. 链接器查看您的目标代码并查看是否存在任何未解析的名称,如果是,则在库中查找这些名称,如果找到它们,则它包含包含它们的目标文件并重复此操作。

Thus only the parts of the static library that are needed are included in your executable. 因此,只有所需的静态库部分包含在您的可执行文件中。

Thus in your case nothing from libfoo will be added to you executable 因此在您的情况下,libfoo中没有任何内容会添加到您的可执行文件中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM