为什么编译和链接C code当是不-lm在某些情况下,有必要吗? [英] Why is -lm not necessary in some cases when compiling and linking C code?

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

问题描述

我有一个示例文件位置:

I have a sample file here:

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

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

当我与编译它的gcc -o sample.c文件在它工作得很好。我可以用 ./一个运行它,它产生的输出 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\n", log(a));
}

它不与 GCC编译-o sample.c文件在。相反,我必须使用的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.

推荐答案

检查拆装,你可能会发现,编译器优化调用日志()出完全在第一种情况下(所以没有什么联系起来),但不是在第二位。在这种特殊情况下,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 code当是不-lm在某些情况下,有必要吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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