I'm very new to C and I have this code:
#include <stdio.h>
#include <math.h>
int main(void)
{
double x = 0.5;
double result = sqrt(x);
printf("The square root of %lf is %lf\n", x, result);
return 0;
}
But when I compile this with:
gcc test.c -o test
I get an error like this:
/tmp/cc58XvyX.o: In function `main':
test.c:(.text+0x2f): undefined reference to `sqrt'
collect2: ld returned 1 exit status
Why does this happen? Is sqrt()
not in the math.h
header file? I get the same error with cosh
and other trigonometric functions. Why?
libm
isn't linked by default even though it contains part of the standard library: #1034398 – Charpentiersqrt(12345)
compiles fine without-lm
. Is the compiler doing the math? – Wagram