问题
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