ccompilationlinkershared-librariesfpic

Does everything that may end up in a shared library always need to be compiled with -fPIC?


I'm building a shared library. I need only one function in it to be public.

The shared library is built from a few object files and several static libraries. The linker complains that everything should be build with -fPIC. All the object files and most static libraries were built without this option.

This makes me ask a number of questions:

  1. Do I have to rebuild every object file and every static library I need for this dynamic lib with -fPIC? Is it the only way?

  2. The linker must be able to relocate object files statically, during linking. Correct? Otherwise if object files used hardcoded constant addresses they could overlap with each other. Shouldn't this mean that the linker has all the information necessary to create the global offset table for each object file and everything else needed to create a shared library?

  3. Should I always use -fPIC for everything in the future as a default option, just in case something may be needed by a dynamic library some day?

I'm working on Linux on x86_64 currently, but I'm interested in answers about any platform.


Solution

    1. You did not say which platform you use but on Linux it's a requirement to compile object files that go into your library as position independent code (PIC). This includes static libraries at least in practice.

    2. Yes. See load time relocation of shared libraries and position independent code pic in shared libraries.

    3. I only use -fPIC when compiling object files that go into libraries to avoid unecessary overhead.