我是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;
}
Run Code Online (Sandbox Code Playgroud)
但是当我编译它时:
gcc test.c -o test
Run Code Online (Sandbox Code Playgroud)
我收到这样的错误:
/tmp/cc58XvyX.o: In function `main':
test.c:(.text+0x2f): undefined reference to `sqrt'
collect2: ld returned 1 exit status
Run Code Online (Sandbox Code Playgroud)
为什么会这样?是sqrt()不是在math.h头文件中?我cosh和其他三角函数有同样的错误.为什么?
我刚刚发现-lmgcc需要这个标志,以便编译一个从数学库中引用函数的程序.我想知道为什么在编译包含其他库(如时间库)的程序时不需要显式链接标志.如果我编写一个time()调用该函数的程序,即使没有链接选项也可以编译没有任何问题.但是如果没有-lm旗帜,那么涉及数学库的程序将无法运行.
任何人都可以解释这种行为背后的原因吗?谢谢你的时间.
我创建了一个小程序,如下所示:
#include <math.h>
#include <stdio.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
int i;
double tmp;
double xx;
for(i = 1; i <= 30; i++) {
xx = (double) i + 0.01;
tmp = sqrt(xx);
printf("the square root of %0.4f is %0.4f\n", xx,tmp);
sleep(1);
xx = 0;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
当我尝试使用以下命令编译它时,我收到编译器错误.
gcc -Wall calc.c -o calc
Run Code Online (Sandbox Code Playgroud)
收益:
/tmp/ccavWTUB.o: In function `main':
calc.c:(.text+0x4f): undefined reference to `sqrt'
collect2: ld returned 1 exit status
Run Code Online (Sandbox Code Playgroud)
如果我用sqrt(10.2)之类的常量替换对sqrt(xx)的调用中的变量,它编译得很好.或者,如果我明确链接如下:
gcc -Wall -lm calc.c -o …Run Code Online (Sandbox Code Playgroud)