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 statusCommon causes
How to fix it
Link -lrt after your objects
- Append -lrt to the link command, after the objects that call clock_gettime.
- Relink and confirm the symbols resolve.
gcc
gcc timer.o -o app -lrtLink 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
ld "undefined reference to `dlopen'" missing -ldl in CIFix ld "undefined reference to `dlopen'" in CI - the dynamic loading functions live in libdl, which must be l…
C++ runtime "version `GLIBCXX_3.4.XX' not found" in CIFix "version `GLIBCXX_3.4.XX' not found" in CI - the binary was built against a newer libstdc++ than the runn…