MacOS X
On MacOS X, the man page for ld
is quite explicit about the -r
option:
-r
Merges object files to produce another mach-o object file with file type MH_OBJECT.
So, if you are on MacOS X, the trouble is that -lm
is not a Mach-O object file, and neither is -lc
. However, in theory, if you have object files main.o
, obj1.o
and obj2.o
and you do:
cp obj1.o ./-lm
cp obj2.o ./-lc
ld -r -o main1.o main.o -lm -lc
then it might work. In practice, it doesn't, and amongst the errors you get:
ld: warning: unexpected dylib (/usr/lib/libm.dylib) on link line
ld: warning: unexpected dylib (/usr/lib/libc.dylib) on link line
However, running:
ld -r -o main1.o -arch x86_64 main.o obj1.o obj2.o
worked without any whingeing from the loader.
Linux
On Linux the man page for ld
is less explicit, but says:
-i
Perform an incremental link (same as option -r).
-r
--relocatable
Generate relocatable output---i.e., generate an output file that can in turn serve as input to ld
. This is often called partial linking. As a side effect, in environments that support standard Unix magic numbers, this option also sets the output file’s magic number to "OMAGIC". If this option is not specified, an absolute file is produced. When linking C++ programs, this option will not resolve references to constructors; to do that, use -Ur
.
When an input file does not have the same format as the output file, partial linking is only supported if that input file does not contain any relocations. Different output formats can have further restrictions; for example some "a.out"-based formats do not support partial linking with input files in other formats at all.
This option does the same thing as -i
.
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 -r
option, there are others where it is not.
Workarounds
The original problem is to establish whether the libraries are present. Why not mimic what autoconf
does, and create a main.c
that would, for preference, contain a reference to a symbol defined in the library, but which could simply contain:
int main(void){return 0;}
and compile and link it with the C compiler:
cc -o main main.c -lm -lc
If it doesn't work, then one of the libraries is missing. If you've already checked that -lc
is present, then you can infer that -lm
is missing.