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?
This question is related to
c
linker
linker-errors
libm
Because you didn't tell the linker about location of math library. Compile with gcc test.c -o test -lm
Add header:
#include<math.h>
Note: use abs(), sometimes at the time of evaluation sqrt() can take negative values which leave to domain error.
abs()- provides absolute values;
example, abs(-3) =3
Include -lm at the end of your command during compilation time:
gcc <filename.extension> -lm
This is a likely a linker error.
Add the -lm
switch to specify that you want to link against the standard C math library (libm
) which has the definition for those functions (the header just has the declaration for them - worth looking up the difference.)
You need to link the with the -lm
linker option
You need to compile as
gcc test.c -o test -lm
gcc (Not g++) historically would not by default include the mathematical functions while linking. It has also been separated from libc onto a separate library libm. To link with these functions you have to advise the linker to include the library -l
linker option followed by the library name m
thus -lm
.
Source: Stackoverflow.com