gpt4 book ai didi

c - 为什么在某些情况下编译和链接 C 代码时不需要 -lm?

转载 作者:太空狗 更新时间:2023-10-29 16:52:59 25 4
gpt4 key购买 nike

我这里有一个示例文件:

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

int main(){
printf("%f\n", log(10));
}

当我用 gcc sample.c -o a 编译它时,它工作得很好。我可以使用 ./a 运行它,它会产生预期的输出 2.302585

然而,当我的文件看起来像这样时:

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

int main(){
double a = 10;
printf("%f\n", log(a));
}

它不能用 gcc sample.c -o a 编译。相反,我必须使用 gcc sample.c -o a -lm 这样我显然可以告诉它“链接数学”......那是我没有真正关注的地方,我为什么不呢必须在第一个例子中链接数学?必须“链接数学”到底意味着什么?自从我使用 C 编译器以来已经有一段时间了,如果这是一个糟糕的问题,请原谅我。

最佳答案

根据 GCC document 可能无法调用数学库函数, 一些内联函数被定义并且可以在某些情况下被调用。

... The GNU C Library provides optimizations for many of the frequently-used math functions. When GNU CC is used and the user activates the optimizer, several new inline functions and macros are defined. These new functions and macros have the same names as the library functions and so are used instead of the latter. In the case of inline functions the compiler will decide whether it is reasonable to use them, and this decision is usually correct.

This means that no calls to the library functions may be necessary, and can increase the speed of generated code significantly. The drawback is that code size will increase, and the increase is not always negligible.

关于c - 为什么在某些情况下编译和链接 C 代码时不需要 -lm?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19486738/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com