为什么在编译和链接 C 代码时在某些情况下不需要 -lm? [英] Why is -lm not necessary in some cases when compiling and linking C code?

查看:17
本文介绍了为什么在编译和链接 C 代码时在某些情况下不需要 -lm?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我这里有一个示例文件:

I have a sample file here:

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

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

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

When I compile it with gcc sample.c -o a it works just fine. I can run it with ./a and it produces the output 2.302585 like expected.

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

Yet, when my file looks like this:

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

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

它不能用 gcc sample.c -o a 编译.相反,我必须使用 gcc sample.c -oa -lm 以便我可以明显地告诉它链接数学"......这就是我不真正遵循的地方,我为什么不必须在第一个例子中链接数学?甚至必须链接数学"到底意味着什么?我已经有一段时间没有使用 C 编译器了,如果这是一个糟糕的问题,请原谅我.

it does not compile with gcc sample.c -o a. Instead, I have to use gcc sample.c -o a -lm so that I can apparently tell it to "link math"...That's where I don't really follow, why wouldn't I have to link math in the first example? And what exactly does it even mean to have to "link math"? It's been a while since I've worked with C compilers, so forgive me if this is poor question.

推荐答案

检查反汇编,你可能会发现编译器一开始就完全优化了对 log() 的调用案例(所以没有什么可以链接的),但不是第二个.在这种特殊情况下,glibc 定义:

Check the disassembly, and you'll likely find that the compiler is optimizing the call to log() out entirely in the first case (so there's nothing to link), but not in the second. In this particular case, glibc defines:

# define M_LN10     2.30258509299404568402

例如,在 math.h 中,任何标准库函数都可以实现为宏,因此它可以在不调用函数的情况下计算其中的一些东西.

in math.h, for instance, and any standard library function can be implemented as a macro, so it can calculate some of these things without a function call.

这篇关于为什么在编译和链接 C 代码时在某些情况下不需要 -lm?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆