/usr/lib/libc.so
is a linker script which tells the linker to pull in the shared library /lib/libc.so.6
, and a non-shared portion, /usr/lib/libc_nonshared.a
.
__libc_csu_init
and __libc_csu_fini
come from /usr/lib/libc_nonshared.a
. They're not being found because references to symbols in non-shared libraries need to appear before the archive that defines them on the linker line. In your case, /usr/lib/crt1.o
(which references them) appears after /usr/lib/libc.so
(which pulls them in), so it doesn't work.
Fixing the order on the link line will get you a bit further, but then you'll probably get a new problem, where __libc_csu_init
and __libc_csu_fini
(which are now found) can't find _init
and _fini
. In order to call C library functions, you should also link /usr/lib/crti.o
(after crt1.o
but before the C library) and /usr/lib/crtn.o
(after the C library), which contain initialisation and finalisation code.
Adding those should give you a successfully linked executable. It still won't work, because it uses the dynamically linked C library without specifying what the dynamic linker is. You'll need to tell the linker that as well, with something like -dynamic-linker /lib/ld-linux.so.2
(for 32-bit x86 at least; the name of the standard dynamic linker varies across platforms).
If you do all that (essentially as per Rob's answer), you'll get something that works in simple cases. But you may come across further problems with more complex code, as GCC provides some of its own library routines which may be needed if your code uses certain features. These will be buried somewhere deep inside the GCC installation directories...
You can see what gcc
is doing by running it with either the -v
option (which will show you the commands it invokes as it runs), or the -###
option (which just prints the commands it would run, with all of the arguments quotes, but doesn't actually run anything). The output will be confusing unless you know that it usually invokes ld
indirectly via one of its own components, collect2
(which is used to glue in C++ constructor calls at the right point).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…