rohitsan rohitsan - 3 months ago 13x
Linux Question

Linking a Static library into a shared library

I am trying to create a shared library using g++ 5.4.0 on Ubuntu Linux.

I have built static libs (.a files) of the Poco C++ library and I want to statically link those into my shared library.

But it is not working.

I have added the following string to my build script:

-Wl,-whole-archive -lPocoFoundation -Wl,-no-whole-archive

g++ complains with the following error message:

relocation R_X86_64_32S against '-ZTVN4Poco15ArchiveStrategyE' can not be used when making a shared object; recompile with -fPIC

Can someone help?


Do what the compiler suggests: Recompile with -fPIC

Explanation: Shared Objects have the requirement, that the addresses in their code do not depend on the memory layout of the binary image in address space. Statically linked code is not bound by this, all addresses in virtual address space are known at link time and hence the code is not required to cope with locations being not determined at compile time.

The -fPIC compiler flag enables compilation of Position Independent Code (PIC). The static libraries you're trying to link were not compiled as PIC that's why the linker complains. The solution is to recompile the static library with PIC enabled.

On a side note: PIC is also a fundamental for Address Space Layout Randomization (ASLR), a security measure with the goal of making the exploitation of vulnerable programs harder.