简体   繁体   中英

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

is there a permanent solution for this problem other than "gcc filename.c -o filename -lm"

sqrt is defined in libm (the maths library). Unless you link with -lm you will get an undefined symbol. Alternatives would include defining your own sqrt function (don't do that).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM