ld "undefined reference to `clock_gettime'" missing -lrt in CI
By Daniel Zoghalchali·Latchkey
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
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 -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.
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.
Frequently asked questions
What causes ""undefined reference to clock_gettime""?
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.
How do I fix "undefined reference to clock_gettime"?