4

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.

Community
  • 1
  • 1
spraff
  • 32,570
  • 22
  • 121
  • 229
  • 1
    I haven ever noticed any problem with setting -fPIC apart from minimally more work to do for compiler and runtime. Usually not a problem. – languitar Aug 26 '14 at 15:51
  • Using -fPIC and -Werror with mingw may result in an error (I would need to check, not on windows right now) – Shade Nov 01 '17 at 02:33
  • @languitar `-fPIC` introduces significant performance penalty because compiler is no longer able to inline and clone functions (as it assumes that it has to preserve symbol interposition semantics). – yugr Oct 22 '18 at 16:04

1 Answers1

0

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.

yugr
  • 19,769
  • 3
  • 51
  • 96