0
votes
#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"

1
To quote man7.org/linux/man-pages/man3/sqrt.3.html - "Link with -lm." That's the official way to use that function.dratenik
Yes there are other permanent "solutions". They're not even worth discussing because of how complicated they're c.f. 4 more keystrokes on the linking command line. The proper solution is to accept that you need to link with -lm, period.Antti Haapala
You need to learn the difference between declarations and definitions. A declaration is telling the compiler that something exists somewhere, but not right here. A definition is the actual implementation of the something. In the case of sqrt the standard <math.h> header declares the function, but the definition is in the m library, which you need to link with using the -l option.Some programmer dude
is there a permanent solution for this problem other than "gcc filename.c -o filename -lm" You're going to have a real fun time writing code to connect to a database that uses SSL to secure its connections if you don't want to link in libraries...Andrew Henle
If adding 4 more characters to a command line is an issue, developing applications might not be the ideal task.Gerhardh

1 Answers

0
votes

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).