Skip to content
Latchkey

ld "undefined reference to `clock_gettime'" missing -lrt in CI

On glibc before 2.17, real-time functions such as clock_gettime and shm_open live in librt. Calling them without -lrt makes the linker report undefined references at link time.

What this error means

Code using clock_gettime or POSIX shared memory compiles but fails to link with undefined references on an older base image, because -lrt is not on the command line.

ld
/usr/bin/ld: timer.o: in function `now':
timer.c:9: undefined reference to `clock_gettime'
collect2: error: ld returned 1 exit status

Common causes

How to fix it

Link -lrt after your objects

  1. Append -lrt to the link command, after the objects that call clock_gettime.
  2. Relink and confirm the symbols resolve.
gcc
gcc timer.o -o app -lrt

Link rt conditionally in CMake

Search for the rt library and link it only where it exists, so newer glibc images (which fold it into libc) are unaffected.

CMakeLists.txt
find_library(RT_LIB rt)
if(RT_LIB)
  target_link_libraries(app PRIVATE ${RT_LIB})
endif()

How to prevent it

  • Link -lrt after the objects that use real-time functions on older glibc, and probe for the library in CMake so the build works on both old and new images.

Related guides

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