使用 math.h 并链接对象文件而不使用 -lm

Ben*_*inB 1 linux gcc

我目前正在阅读 Advanced Linux Programming 并且在 2.3.3 节中说,如果我使用 math.h 中的某些函数,我必须使用 -lm 链接目标文件。但我很确定我已经使用了一些数学函数,如 sqrt、pow 或 log,而无需指定使用此共享库。

你看到问题出在哪里了吗?

谢谢

Mat*_*Mat 6

如果您想保持代码/makefile 的可移植性-lmmath.h则在使用函数时应始终使用。

该头文件中的一些内容是宏(显然不需要额外的库),但没有指定(除了少数几个)。一些其他函数可能由您的编译器作为内置函数实现(甚至直接由特定于处理器的操作码替换)、内联等......因此您的代码的正确链接也可能取决于优化器设置和您的确切编译器/版本正在使用。

例如:

#include <stdio.h>
#include <math.h>

int main()
{
    double d = 0.2;
    fprintf(stdout, "%f\n", sqrt(d));
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

在 Linux 上使用 GCC 4.5.1:

$ gcc -o t t.c
/tmp/cczCfJsj.o: In function `main':
t.c:(.text+0x30): undefined reference to `sqrt'
collect2: ld returned 1 exit status

$ gcc -O3 -o t t.c
# ok, compiled and linked fine
Run Code Online (Sandbox Code Playgroud)

因此,为了避免让自己头疼,只需添加-lm.