未定义的引用`roundf' - C语言

B. *_*age 1 c compiler-errors compilation math.h ubuntu-14.04

我是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);
    }
Run Code Online (Sandbox Code Playgroud)

我收到的错误是,

    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
Run Code Online (Sandbox Code Playgroud)

非常感谢任何帮助,谢谢!

P.P*_*.P. 9

链接数学库:

cc example.c -o example -lm
Run Code Online (Sandbox Code Playgroud)

数学库函数不是默认链接的标准C库的一部分.所以你需要自己链接.

关于为什么它不是libc的一部分,有一个有趣的线程:

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

  • @ MarsellusWallace-请接受这个答案. (2认同)