使用gcc test.c
,第一份代码样例可以编译,而第二份则不能。为什么?
它们都需要显式链接数学库才能运行(即gcc test.c -lm
)。
第一份样例:
#include <stdio.h>
#include <math.h>
int main () {
printf("%lf\n", sqrt(4.0) );
return 0;
}
第二个样例:
#include <math.h>
#include <stdio.h>
double sqrt2(double a) { return sqrt(a); }
int main() {
printf("%lf\n", sqrt(4.0));
printf("%lf\n", sqrt2(4.0));
return 0;
}
第二个示例程序出现连接错误:
/tmp/ccuYdso7.o: In function `sqrt2':
test.c:(.text+0x13): undefined reference to `sqrt'
collect2: error: ld returned 1 exit status
gcc -v:
Using built-in specs.
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-pc-linux-gnu/8.1.0/lto-wrapper
Target: x86_64-pc-linux-gnu
Configured with: /build/gcc/src/gcc/configure --prefix=/usr --libdir=/usr/lib --libexecdir=/usr/lib --mandir=/usr/share/man --infodir=/usr/share/info --with-bugurl=https://bugs.archlinux.org/ --enable-languages=c,c++,ada,fortran,go,lto,objc,obj-c++ --enable-shared --enable-threads=posix --enable-libmpx --with-system-zlib --with-isl --enable-__cxa_atexit --disable-libunwind-exceptions --enable-clocale=gnu --disable-libstdcxx-pch --disable-libssp --enable-gnu-unique-object --enable-linker-build-id --enable-lto --enable-plugin --enable-install-libiberty --with-linker-hash-style=gnu --enable-gnu-indirect-function --enable-mul
Thread model: posix
gcc version 8.1.0 (GCC)
在主函数中使用
sqrt
时不会出现链接错误。这是为什么呢?我还检查了clang,但没有-lm
无法编译(链接错误)。
sqrt(4.0)
被优化掉了。 - Eugene Sh.