Reputation: 33445
I just got this error when compiling some plugins for my new toy (on gcc/g++ on Linux):
relocation R_X86_64_32 can not be used when making a shared object; recompile with -fPIC
I basically understand why PIC is needed but, within the CMake system, the solution seems to be this:
IF (CMAKE_SYSTEM_PROCESSOR STREQUAL "x86_64")
SET_TARGET_PROPERTIES (${PLUGIN_BASE_LIB} PROPERTIES COMPILE_FLAGS "-fPIC")
ENDIF (CMAKE_SYSTEM_PROCESSOR STREQUAL "x86_64")
I don't understand why this solution is conditional.
The follow-up seems to suggest that -fPIC should be used basically everywhere except 32-bit Linux, which suggests that the above is not portable.
Should I always use -fPIC? Will there be any adverse effects?
${PLUGIN_BASE_LIB}
needs to be statically linked to both the main executable, and statically the various shared libraries which are the plugins.
Upvotes: 4
Views: 840
Reputation: 21954
Ideally you want to build two versions of code: one for the main executable and one for the library. The first will need to be compiled with -fPIE
(which is default in modern distros) and the second with -fPIC
. As you point out this does not depend on target architecture.
You can compile only one version with -fPIC
but then main executable will be suboptimal because -fPIC
forces compiler to obey symbol interposition rules which significantly limits it's ability to optimize code e.g. inline and clone functions.
Upvotes: 0