Why does including -fPIC to compile a static libra

2019-05-20 08:49发布

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条回答
SAY GOODBYE
2楼-- · 2019-05-20 09:22

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.

查看更多
登录 后发表回答