C语言错误:未定义对 `roundf' 的引用

3

我是C语言的新手,经常遇到同样的错误。我在nano文本编辑器中输入代码,并在Linux终端中编译。我的操作系统是Ubuntu 14.04。以下是一个无法编译的代码示例:

    #include <math.h>
    #include <stdio.h>
    int main()
    {
        float x = 23.33f;
        x = roundf(x);
        printf("%f\n", x);
        return (0);
    }

我收到的错误是:
    cc     example.c   -o example
    /tmp/ccWV0Or8.o: In function `main':
    example.c:(.text+0x1d): undefined reference to `roundf'
    collect2: error: ld returned 1 exit status
    make: *** [example] Error 1

非常感谢您的帮助!

1个回答

14

使用数学库进行链接:

cc example.c -o example -lm

数学库函数不是默认链接的标准C库的一部分,因此您需要自己链接它。

有一个关于为什么它不是libc的一部分的有趣讨论:

为什么在C中必须链接数学库?


1
非常感谢您的帮助!您的解决方案起作用了。 - B. Standage

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接