This question already has an answer here:
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?
The math library must be linked in when building the executable. How to do this varies by environment, but in Linux/Unix, just add -lm
to the command:
gcc test.c -o test -lm
The math library is named libm.so
, and the -l
command option assumes a lib
prefix and .a
or .so
suffix.
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
.
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.)
Because you didn't tell the linker about location of math library. Compile with gcc test.c -o test -lm
You must link the header file math.h
with your code. You can do this by typing -lm
after your command.
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
来源:https://stackoverflow.com/questions/10409032/why-am-i-getting-undefined-reference-to-sqrt-error-even-though-i-include-math