Skip to content
Latchkey

Link error "recompile with -fPIC" building a shared library in CI

The linker is building a shared library from object files that were compiled without position-independent code. Shared objects require PIC, so the linker refuses and tells you to recompile with -fPIC.

What this error means

The link step fails with "relocation R_X86_64_32 against ... can not be used when making a shared object; recompile with -fPIC", usually when a static library is linked into a shared one.

ld
/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
collect2: error: ld returned 1 exit status

Common causes

A static dependency was built without PIC

A static archive linked into a shared library was compiled without -fPIC, so its relocations are not usable in a shared object.

POSITION_INDEPENDENT_CODE not set on the target

The CMake target that becomes a shared library or is linked into one did not enable PIC.

How to fix it

Enable position-independent code in CMake

Set POSITION_INDEPENDENT_CODE on the target (or globally) so all objects are built with -fPIC.

CMakeLists.txt
set_target_properties(util PROPERTIES POSITION_INDEPENDENT_CODE ON)

Set it project-wide for consistency

Enable PIC for every target at configure time so static objects can be linked into shared libraries.

Terminal
cmake -S . -B build -DCMAKE_POSITION_INDEPENDENT_CODE=ON

How to prevent it

  • Build static libraries that feed shared ones with PIC.
  • Set CMAKE_POSITION_INDEPENDENT_CODE=ON when producing shared libraries.
  • Keep PIC consistent across all objects that link together.

Related guides

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