Search code examples
cgcccompilationshared-librariesposition-independent-code

Mixing fPIC and non-fPIC object modules


Environment: Ubuntu 16.04

In my experiment, I ran the following commands:

gcc -c 1.c
gcc -c -fPIC 2.c
gcc -shared 1.o 2.o -o libmyxxx.so

The functions that I need to expose are all defined in 2.c via extern "C" declarations. These functions internally call other functions that are defined in 1.c.

Note that I did not apply -fPIC to 1.c. Still everything seems to compile/link fine without any warnings.

Can we conclude that -fPIC must be applied only to those source files that expose external functions?

In the larger picture, I have a bunch of archive (.a) files that may not have been compiled with -fPIC flag. I need to create a custom shared library that would link with these archive files. If my assumption is valid, I am thinking it would be okay to link with these archive files. Appreciate your thoughts. Regards.


Solution

  • Can we conclude that -fPIC must be applied only to those source files that expose external functions?

    No we can't. The only purpose of -fPIC is ensure that produced machine code can be linked into position-independent binary. Nevertheless it is possible that some code appears to be PIC-ready even if source was compiled without -fPIC. It may be short self-containing functions without external dependencies, whatever that will not require auxiliary data structures in generated object file, like PLT and GOT entries.

    Anyway linker will fail with comprehensive error message if your object file cannot be linked into position-independent binary. And you need to recompile it with this magic option.

    So you should always put -fPIC to CFLAGS of your shared library just to save your own time and avoid wasteful recompilations.