将代码与 `floor();`、`ceil();` 和 `pow();` 链接时出错

ch3*_*v3k 2 c flags math.h linker-errors undefined-reference

我在 GNU/Linux Debian 8.5 下编码

我有一个简单的程序。

如果我用gcc prog.c它编译它就可以了!

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

int main(int argc, char const *argv[]) {

    float _f = 3.1415f;

    floor(_f);
    ceil(_f);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

但是,如果我添加pow(),它会说它找不到pow,我需要添加gcc prog.c -lm以使其正确。

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

int main(int argc, char const *argv[]) {

    float _f = 3.1415f;

    floor(_f);
    ceil(_f);
    pow(_f, 2);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

如果我是对的,pow(), ceil(),floor()都是来自<math.h>?

那么,为什么不floor()ceil()抛出一个编译错误,并pow()确实,没有-lm标志?

rod*_*igo 5

从技术上讲,所有这些都需要-lm工作。他们所有的man页面都包含这一行:

与 -lm 链接。

但是你的不是编译器错误而是链接器错误,也就是说你的程序编译得很好,但是在链接时如果你不使用-lm它就无法找到 的实现,pow()但它实际上找到了ceil().

那可能是因为在您的体系结构/配置中ceil()是内联或内在函数,也许有一个简单的 CPU 指令可以做到这一点,因此不需要任何库。但pow()不是这样你需要链接libm

更新:我刚刚做了一些实验,-O0你的所有功能都需要-lm-O2只有pow(). 关于修改一下,我发现文件/usr/include/bits/mathinline.h与内嵌的实现ceil()floor()...


归档时间:

查看次数:

1029 次

最近记录:

9 年,4 月 前