链接器ld
//link.c
#include <stdio.h>
#include <stdlib.h>
int main()
{
printf("%f\n", square(0.3));
system("pause");
return 0;
}
//square.c
double square(double x)
{
return x*x;
}
直接使用ld链接目标文件,输出如下:
D:\C陷阱与缺陷\test\test>ld link.o square.o -o rlink.exe
link.o:link.c:(.text+0xa): undefined reference to `__main'
link.o:link.c:(.text+0x30): undefined reference to `printf'
使用gcc链接目标文件,输出如下:
D:\C陷阱与缺陷\test\test>gcc link.o square.o -o rlink.exe
- 在link.c中已经include了头文件了,为什么使用ld还无法识别mian和printf?
因为ld默认情况下并不链接任何库。
使用gcc链接的时候,gcc能自动加入一些默认的链接。
使用gcc 的--verbose(-v)选项,可以看到编译链接的细节。
能够看到gcc默认的链接的一些东西,例如
D:\C陷阱与缺陷\test\test>gcc link.o square.o -v -o rlink.exe
Using built-in specs.
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=f:/programes/mingw/bin/../libexec/gcc/mingw32/4.6.2/lto-wrap
per.exe
Target: mingw32
Configured with: ../gcc-4.6.2/configure --enable-languages=c,c++,ada,fortran,obj
c,obj-c++ --disable-sjlj-exceptions --with-dwarf2 --enable-shared --enable-libgo
mp --disable-win32-registry --enable-libstdcxx-debug --enable-version-specific-r
untime-libs --build=mingw32 --prefix=/mingw
Thread model: win32
gcc version 4.6.2 (GCC)
COMPILER_PATH=f:/programes/mingw/bin/../libexec/gcc/mingw32/4.6.2/;f:/programes/
mingw/bin/../libexec/gcc/;f:/programes/mingw/bin/../lib/gcc/mingw32/4.6.2/../../
../../mingw32/bin/
LIBRARY_PATH=f:/programes/mingw/bin/../lib/gcc/mingw32/4.6.2/;f:/programes/mingw
/bin/../lib/gcc/;f:/programes/mingw/bin/../lib/gcc/mingw32/4.6.2/../../../../min
gw32/lib/;f:/programes/mingw/bin/../lib/gcc/mingw32/4.6.2/../../../
COLLECT_GCC_OPTIONS='-v' '-o' 'rlink.exe' '-mtune=i386' '-march=i386'
f:/programes/mingw/bin/../libexec/gcc/mingw32/4.6.2/collect2.exe -Bdynamic -o r
link.exe f:/programes/mingw/bin/../lib/gcc/mingw32/4.6.2/../../../crt2.o f:/prog
rames/mingw/bin/../lib/gcc/mingw32/4.6.2/crtbegin.o -Lf:/programes/mingw/bin/../
lib/gcc/mingw32/4.6.2 -Lf:/programes/mingw/bin/../lib/gcc -Lf:/programes/mingw/b
in/../lib/gcc/mingw32/4.6.2/../../../../mingw32/lib -Lf:/programes/mingw/bin/../
lib/gcc/mingw32/4.6.2/../../.. link.o square.o -lmingw32 -lgcc_eh -lgcc -lmoldna
me -lmingwex -lmsvcrt -ladvapi32 -lshell32 -luser32 -lkernel32 -lmingw32 -lgcc_e
h -lgcc -lmoldname -lmingwex -lmsvcrt f:/programes/mingw/bin/../lib/gcc/mingw32/
4.6.2/crtend.o