简体   繁体   English

为什么即使我包含 math.h 标头,也会收到“对 sqrt 的未定义引用”错误? 除了添加 -lm 之外,还有其他永久解决方案吗?

[英]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;

} }

when i compile the program an error message is shown in the terminal window.当我编译程序时,终端窗口中会显示一条错误消息。

/usr/bin/ld: /tmp/cc8GnBrR.o: in function 'main': distance2.c:(.text+0xa4): undefined reference to 'sqrt' collect2: error: ld returned 1 exit status /usr/bin/ld: /tmp/cc8GnBrR.o: 在函数 'main': distance2.c:(.text+0xa4): 未定义对 'sqrt' collect2 的引用:错误:ld 返回 1 退出状态

is there a permanent solution for this problem other than "gcc filename.c -o filename -lm"除了“gcc filename.c -o filename -lm”之外,是否有针对此问题的永久解决方案

sqrt is defined in libm (the maths library). sqrtlibm (数学库)中定义。 Unless you link with -lm you will get an undefined symbol.除非你用-lm链接,否则你会得到一个未定义的符号。 Alternatives would include defining your own sqrt function (don't do that).替代方法包括定义您自己的sqrt函数(不要那样做)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 仅当参数不是常量时,来自math.h的sqrt才会导致链接器错误“对sqrt的未定义引用” - sqrt from math.h causes linker error “undefined reference to sqrt” only when the argument is not a constant 在Ubuntu上对exp的未定义引用(包括math.h和使用-lm链接) - Undefined reference to exp on Ubuntu (including math.h and linking with -lm) 为什么即使我定义了我正在使用的命令,也会得到对另一个文件的未定义引用? - Why am I getting an undefined reference to another file, even though I define the command I am using? 没有math.h包含-sqrt函数返回值? - No math.h include - sqrt function return value? 快速反演算法比math.h 1 / sqrt函数慢 - fast inversion algorithm slower than math.h 1/sqrt function C - 对“sqrt”的未定义引用,即使使用'-lm' - C - undefined reference to “sqrt” even with '-lm' 为什么会出现“未定义引用”错误? - Why am I getting “undefined reference to” error? 对“只有一些 math.h”函数的未定义引用 - undefined reference to “only some math.h” functions 为什么 sqrt() 和 abs() 在 C 程序中工作而不包含 math.h 或 stdlib.h? - why sqrt() and abs() work in C program without including math.h or stdlib.h? 即使我包含正确的头文件,为什么会出现“未定义的引用”错误? - Why do I get “undefined reference” errors even when I include the right header files?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM