未定义对“ sqrt”,“ log”的引用,

时间:2019-08-20 02:12:47

标签: c

当我编译这段代码时:

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

int main() {

    char str[] = "3.6";

    double res = atof(str);

    printf("%f\n", sqrt(res));

    return 0;
}

我收到此错误:

    ====================[ Build | untitled12 | Debug ]==============================
/snap/clion/81/bin/cmake/linux/bin/cmake --build /home/abdo/CLionProjects/untitled12/cmake-build-debug --target untitled12 -- -j 4
[ 50%] Linking C executable untitled12
/usr/bin/ld: CMakeFiles/untitled12.dir/main.c.o: in function `main':
/home/abdo/CLionProjects/untitled12/main.c:11: undefined reference to `sqrt'
collect2: error: ld returned 1 exit status
make[3]: *** [CMakeFiles/untitled12.dir/build.make:84: untitled12] Error 1
make[2]: *** [CMakeFiles/Makefile2:73: CMakeFiles/untitled12.dir/all] Error 2
make[1]: *** [CMakeFiles/Makefile2:85: CMakeFiles/untitled12.dir/rule] Error 2
make: *** [Makefile:118: untitled12] Error 2

当我将'sqrt'替换为'log'或'ln'时,我也会遇到相同的错误...

编译器:cc(Ubuntu 8.3.0-6ubuntu1)8.3.0

1 个答案:

答案 0 :(得分:1)

编译时必须链接数学库。在源文件或目标文件之后,将-lm标志添加到您的gcc命令中。