[英]sqrt from math.h causes linker error “undefined reference to sqrt” only when the argument is not a constant
我创建了一个小程序,如下所示:
#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;
}
当我尝试使用以下命令对此进行编译时,出现编译器错误。
gcc -Wall calc.c -o calc
返回:
/tmp/ccavWTUB.o: In function `main':
calc.c:(.text+0x4f): undefined reference to `sqrt'
collect2: ld returned 1 exit status
如果我将sqrt(xx)调用中的变量替换为sqrt(10.2)之类的常量,则编译就可以了。 或者,如果我明确链接如下:
gcc -Wall -lm calc.c -o calc
它也可以正常工作。 谁能告诉我是什么原因造成的? 我很长时间以来一直是C程序员(并且我已经使用math.h编写了类似的小程序),但从未见过这样的事情。
我的gcc版本如下:
$ gcc --version
gcc (Ubuntu 4.3.3-5ubuntu4) 4.3.3
Copyright (C) 2008 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
$
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.