Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

g++ linking a static library into a dynamic library (without -fPIC)

I am trying to link with g++ a static library (staticLib.a) into a dynamic library (dynamicLib.so) using:

g++  *.o -Wl,--whole-archive staticLib.a -Wl,--no-whole-archive -shared -o dynamicLib.so

And I got the same error as here:

/usr/bin/ld: staticLib.a(object.o): relocation R_X86_64_32 against `.rodata' can not be used when making a shared object; recompile with -fPIC staticLib.a(object.o): error adding symbols: Bad value collect2: error: ld returned 1 exit status

I read several topics, but I could not find the answer I am looking for. staticLib.a was not compiled as position-independent code (PIC). According to the link above, it seems to be mandatory. However, staticLib.a is a library from another project over which I do not have control.

My first thought was to extract the objects *.o usingar -x (as explained in this second link). But the problem remains the same as the object was not compiled with -fPIC.

My second thought was to create my own Makefile to recompile staticLib.a with -fPIC in my project (I do not want to mess up the existing project). But I am not sure it is a good way to do...

So my question is the following: Is there any possible way to link a static library (compiled without -fPIC) into a dynamic one ?

Related topics:

  • Can I build a shared library by linking static libraries?

  • Linking a Static library into a shared library

  • how to link static library into dynamic library in gcc

  • "relocation R_X86_64_32S against " linking Error

like image 385
Nicolas Avatar asked Oct 29 '22 14:10

Nicolas


1 Answers

So my question is the following: Is there any possible way to link a static library (compiled without -fPIC) into a dynamic one ?

As providing position independent code requires compilation no practically it is not possible to change already compiled code. Theoretically you may reverse engineer source code from binary and recompile, but that would be completely ineffective solution. So you have to (re)compile orginal project with -fPIC passed.

like image 52
Slava Avatar answered Nov 15 '22 06:11

Slava