为什么包含-fPIC来编译静态库会在运行时导致分段错误? [英] Why does including -fPIC to compile a static library cause a segmentation fault at run time?
问题描述
我正在使用g ++并使用-fPIC选项来编译C ++静态库。我必须使用-fPIC选项,因为最终该库将与其他静态库链接以形成动态库。
I'm compiling C++ static library with g++ and using the -fPIC option. I must use the -fPIC option because eventually this library will be linked with other static libraries to form a dynamic library.
在本地测试静态库时,它可以完全正常工作当我不包括-fPIC选项时,它很好。但是,一旦我使用-fPIC编译该库,则在调用这些函数之一时会在运行时收到分段错误错误。
When I test the static library locally, it works completely fine when I don't include the -fPIC option. But as soon as I compile the library with -fPIC, I receive a segmentation fault error at run-time when calling one of the functions.
可能包括-fPIC的原因是什么?编译静态库会在运行时导致分段错误?
What reasons could including -fPIC to compile a static library cause a segementation fault at run-time?
推荐答案
应该在运行时加载动态库-
A dynamic library is supposed to be loaded at run-time and can therefore not have position-dependent code.
另一方面,静态库只是对象文件的存档。
A static library, on the other hand, is just an archive of object files.
与动态库链接时,链接程序将库的名称添加到可执行文件中,因此加载程序可以在加载程序时加载它。当链接器与静态库链接时,它基本上会提取目标文件并像其他任何目标文件一样链接它们。
When linking with a dynamic library, the linker adds the name of the library in the executable file, so the loader can load it when it loads the program. When the linker links with a static library, it basically extracts the object files and links with them like any other object file.
因此,除非您在所有其他对象都创建了可执行文件的情况下文件是与位置无关的(您在程序代码中使用 -fPIC
),则无法与使用与位置无关的代码的静态库链接,生成的可执行文件为只是没有为此而设置。
So unless you create an executable where all other object files are position-independent (you use -fPIC
for your the programs code) then you can't link with a static library which uses position-independent code, the generated executable is simply not set up for it.
这篇关于为什么包含-fPIC来编译静态库会在运行时导致分段错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!