Skip to content
Latchkey

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.

ld output
/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 output

Common 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.

Terminal
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

  1. If a third-party .a is not PIC, rebuild it from source with -fPIC.
  2. Or link it statically into a non-PIE executable instead of a shared object.
  3. Set CMAKE_POSITION_INDEPENDENT_CODE ON so all targets are PIC-consistent.

How to prevent it

  • Set CMAKE_POSITION_INDEPENDENT_CODE ON for projects that produce shared libraries.
  • Build static libraries with -fPIC if they may be embedded into .so files.
  • Use PIC-built distributions of third-party static libraries.

Related guides

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →