[英]sqrt from math.h causes linker error “undefined reference to sqrt” only when the argument is not a constant
[英]Why am I getting “undefined reference to sqrt” error even though I include math.h header? is there a permanent solution other than adding -lm?
#include <stdio.h>
#include <math.h>
int main()
{
int x, y, x1, x2, y1, y2;
float distance;
//take the 1st points coordinates x axis and y axis
printf("Enter the coordinates of 1st point: ");
scanf("%d %d", &x1, &y1);
//take the 2st points coordinates x axis and y axis
printf("Enter the coordinates of 2nd point: ");
scanf("%d %d", &x2, &y2);
x = x2 - x1;
y = y2 - y1;
distance = sqrt((x * x) + (y * y));
//display result
printf("Distance = %.2f", distance);
return 0;
}
当我编译程序时,终端窗口中会显示一条错误消息。
/usr/bin/ld: /tmp/cc8GnBrR.o: 在函数 'main': distance2.c:(.text+0xa4): 未定义对 'sqrt' collect2 的引用:错误:ld 返回 1 退出状态
除了“gcc filename.c -o filename -lm”之外,是否有针对此问题的永久解决方案
sqrt
在libm
(数学库)中定义。 除非你用-lm
链接,否则你会得到一个未定义的符号。 替代方法包括定义您自己的sqrt
函数(不要那样做)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.