ld "relocation R_X86_64_... can not be used" - Recompile with -fPIC
The linker tried to put a non–position-independent object into a shared library. Shared objects need position-independent code; an object compiled without -fPIC has absolute relocations that cannot live in a .so.
What this error means
Linking a shared library (or a PIE executable) fails with "relocation R_X86_64_32 against ... can not be used when making a shared object; recompile with -fPIC". It typically involves a static library or object built without PIC.
/usr/bin/ld: libutil.a(util.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 outputCommon causes
Objects compiled without -fPIC
A static library or object built without -fPIC is being linked into a shared library or PIE binary. Its absolute relocations are invalid in position-independent output.
A prebuilt static lib that is not PIC
A third-party .a compiled without PIC cannot be embedded into a .so. You must rebuild it with PIC or link it differently.
How to fix it
Recompile the objects with -fPIC
Build the offending objects/library with position-independent code.
g++ -fPIC -c util.cpp -o util.o
# CMake - enable PIC for the target (or globally):
# set_target_properties(util PROPERTIES POSITION_INDEPENDENT_CODE ON)
# or set(CMAKE_POSITION_INDEPENDENT_CODE ON)Rebuild the static dependency with PIC
- If a third-party
.ais not PIC, rebuild it from source with-fPIC. - Or link it statically into a non-PIE executable instead of a shared object.
- Set
CMAKE_POSITION_INDEPENDENT_CODE ONso all targets are PIC-consistent.
How to prevent it
- Set
CMAKE_POSITION_INDEPENDENT_CODE ONfor projects that produce shared libraries. - Build static libraries with
-fPICif they may be embedded into.sofiles. - Use PIC-built distributions of third-party static libraries.