Reputation: 77
I have a C++ source tree developed under Ubuntu 12.04 using clang++ 3.2 that builds some libraries, then compiles some applications with these libraries and the usual collection of other various system libraries. Two puzzles. Client reports that code fails to build with undefined reference to clock_gettime(). Sure enough, I did not include the obligatory "-lrt" in the build logic (scons).
First puzzle: This compiles, links and executes correctly and without complaint on my system even though I do not specify "-lrt" anywhere! How does this symbol get correctly resolved? I suspect it is because the application links against a dynamic library that itself requires librt but I don't understand the logic behind why this would happen?
Second puzzle: Assuming a satisfactory explanation of how clock_gettime() gets resolved without "-lrt", why would this happen on my system but not on client's very similar setup?
"... a riddle, wrapped in a mystery, inside an enigma" --- Winston Churchill
Suggestions for tools to reveal what is really going on here would be most welcomed.
Upvotes: 2
Views: 274
Reputation: 5172
From SUSv4 (Utilities/c99):
-l rt
This option shall make available all interfaces referenced in <aio.h>
, <mqueue.h>
, <sched.h>
, <semaphore.h>
, and <spawn.h>
, interfaces marked as optional in <sys/mman.h>
, interfaces marked as ADV (Advisory Information) in <fcntl.h>
, and interfaces beginning with the prefix clock_
and time_
in <time.h>
. An implementation may search this library in the absence of this option.
I presume the above suffices to at least justify why this behavior is allowed by POSIX.
Most likely the involved systems are different in this regard. For example, clock_gettime()
might be implemented in libc
for you, but in librt
for your client. Don't take chances: use a portable -l rt
and forget about the issue.
A more obvious example is -l xnet
, which behaves similarly according to POSIX, but, at least on Gentoo, Debian and Ubuntu Linux systems, compiling with -l xnet
actually yields an error. (libxnet
purportedly contains the implementation for the UNIX sockets interface.)
If you want to further investigate the issue, try ldd
in GNU/Linux systems. ldd
should display the dynamic dependencies for your binary. I'd bet that clock_gettime()
is simply implemented in libc.so
.
Upvotes: 4