Why does including -fPIC to compile a static library cause a segmentation fault at run time?

半腔热情 提交于 2019-12-22 18:34:22

问题


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.

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.

What reasons could including -fPIC to compile a static library cause a segementation fault at run-time?


回答1:


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.

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.



来源:https://stackoverflow.com/questions/37842036/why-does-including-fpic-to-compile-a-static-library-cause-a-segmentation-fault

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!