-
math.h
Code:
# include <stdio.h>
# include <stdlib.h>
# include <math.h>
int main ()
{
double k;
double x;
printf ("Enter a number ... \n");
scanf ("%f", &k);
x = sqrt (k);
// x = cos (k);
printf ("Square root is %f\n", x);
return 0;
}
Error:
/tmp/cc2E1F0F.o(.text+0x3e): In function `main':
: undefined reference to `sqrt'
collect2: ld returned 1 exit status
I am working in linux platform and i do not why do i get this error. I think non of the math.h functions are not working. But I included math.h. any suggestions?
-
I have no problem in compiling your code, I'm using codeblocks with mingw - windows xp. Just a suggestion you must use %lf for the conversion specifier of double.
-
Dial "m" ;) for linking to the math library that contains the definition of sqrt().
Explicitly specify that you need to link in the math lib at compile time, as in
-
Quote:
Originally Posted by
itCbitC
While you are at it, I would suggest that you turn on compiler warnings:
Code:
gcc -Wall -W -pedantic yourprogam.c -o yourprogram -lm
You might see some helpful stuff like
Code:
yourprogram.c: In function ‘main’:
yourprogram.c:9: warning: format ‘%f’ expects type ‘float *’, but argument 2 has type ‘double *’
Watchtower's suggestion tells you how to fix it, but I think it's nice that the compiler can give you a hint that there's a problem so you know where to look (in case Watchtower is not around when you wonder why you get the wrong answer from the program).
D.