【发布时间】:2021-12-19 21:03:06
【问题描述】:
我对 C 很陌生,我有这个代码:
#include <stdio.h>
#include <math.h>
int main(void)
{
double x = 0.5;
double result = sqrt(x);
printf("The square root of %lf is %lf\n", x, result);
return 0;
}
但是当我编译这个时:
gcc test.c -o test
我收到这样的错误:
/tmp/cc58XvyX.o: In function `main':
test.c:(.text+0x2f): undefined reference to `sqrt'
collect2: ld returned 1 exit status
为什么会这样? sqrt() 不在 math.h 头文件中吗? cosh 和其他三角函数也出现同样的错误。为什么?
【问题讨论】:
-
这里有一些关于为什么
libm没有默认链接的猜测,即使它包含标准库的一部分:stackoverflow.com/questions/1033898/… -
在使用整数文字时是否有原因不会引发错误? IE。
sqrt(12345)在没有-lm的情况下编译得很好。编译器在做数学吗? -
按照接受的答案后它仍然无法正常工作,对于一个简单的函数来说这是多么累人的操作,但是使用确切的数字调用 sqrt() 仍然可以工作
标签: c linker linker-errors libm