Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

g++ compile error: `.rodata' can not be used when making a shared object; recompile with -fPIC

Tags:

I am using the command:
g++ --std=c++11 -fPIC -Iincludes parser.cpp lib/main-parser.o lib/lib.a

To compile a C++ program on Debian 9. But I am getting the below error message: /usr/bin/ld: lib/lib.a(csdocument.o): relocation R_X86_64_32 against '.rodata' can not be used when making a shared object; recompile with -fPIC /usr/bin/ld: final link failed: Nonrepresentable section on output collect2: error: ld returned 1 exit status

I have already seen the thread: Compilation fails with "relocation R_X86_64_32 against `.rodata.str1.8' can not be used when making a shared object"

However, I have tried adding the -fPIC argument however it strangely gives the same error message, along with "recompile with -fPIC"

Any ideas would be appreciated. I have tried compiling this on my University's RedHat systems and it works fine there. I'm thinking it could be a missing dependency, but I've been unable to find any answers.

Thanks in advance

like image 999
Polymer Avatar asked Oct 19 '17 10:10

Polymer


2 Answers

As it seems gcc is trying to produce a position-independent executable ("shared object" is the hint), tell it not to:

g++ --std=c++11 -no-pie -Iincludes parser.cpp lib/main-parser.o lib/lib.a 

It seems that g++ produces position-independent executables by default on your system. Other systems would require -pie to do so. Using -no-pie should create a "regular" (position dependent) executable.

(The error is a result of trying to link an object file that was compiled as non-position-independent into an executable that is supposed to be position-independent).

like image 123
davmac Avatar answered Sep 22 '22 11:09

davmac


/usr/bin/ld: lib/lib.a(csdocument.o): relocation R_X86_64_32 against '.rodata' \ can not be used when making a shared object; recompile with -fPIC 

This linker error is telling you that the object file csdocument.o in the static library lib/lib.a is not Position Independent Code and hence cannot be linked with your PIE program. So you need to recompile the source files of lib/lib.a with -fPIC, then rebuild the static library, then link it with your PIE program. If you don't have control of the libary sources then request a PIC build from its supplier.

(Others have questioned why you should need to build a PIE target at all since it's not a shared library. In Debian 9, GCC produces PIE executables by default, whether programs or shared libraries. The same goes for Ubuntu as of 17.04. )

like image 25
Mike Kinghan Avatar answered Sep 22 '22 11:09

Mike Kinghan