Running Debian/Linux x86_64 with GNU ld 2.21.
Quite simply, if I link with
ld -o main main.o /usr/lib/crti.o /usr/lib/crt1.o /usr/lib/crtn.o -lc -lm
It works, but when I link with
ld -r -o main1.o main.o /usr/lib/crti.o /usr/lib/crt1.o /usr/lib/crtn.o -lc -lm
It complains
ld: cannot find -lc
ld: cannot find -lm
I’m not actually trying to compile code this way, but rather I’m trying to figure out why someone else’s test to see if a library exists is not working. (Thus I don’t really understand what’s going on with ld… usually I just use GCC to link)
Why would telling ld to link in a relocatable fashion make it suddenly unable to find libraries? If I just want to test that -lm exists, what should I do besides
ld -r -lm
so that it will find the library?
If you want to see the source that I’m dealing with, you can download it here: https://github.com/jeremysalwen/ESPS (note, that the first commit is the original source code, and the subsequent ones are changes I have personally made.)
MacOS X
On MacOS X, the man page for
ldis quite explicit about the-roption:So, if you are on MacOS X, the trouble is that
-lmis not a Mach-O object file, and neither is-lc. However, in theory, if you have object filesmain.o,obj1.oandobj2.oand you do:then it might work. In practice, it doesn’t, and amongst the errors you get:
However, running:
worked without any whingeing from the loader.
Linux
On Linux the man page for
ldis less explicit, but says:Reading between the lines, this also takes object files and converts them to object files; it does not add libraries into the mix. If you think about it, object files are not created containing references to libraries.
So, although there might be platforms where it is possible to specify libraries to the linker (loader) when using the
-roption, there are others where it is not.Workarounds
The original problem is to establish whether the libraries are present. Why not mimic what
autoconfdoes, and create amain.cthat would, for preference, contain a reference to a symbol defined in the library, but which could simply contain:and compile and link it with the C compiler:
If it doesn’t work, then one of the libraries is missing. If you’ve already checked that
-lcis present, then you can infer that-lmis missing.