Why do I get an "undefined sqrt link" even though I include the math.h header?
I am 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 message:
/tmp/cc58XvyX.o: In function `main': test.c:(.text+0x2f): undefined reference to `sqrt' collect2: ld returned 1 exit status Why is this happening? 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 when creating the executable. How to do this depends on the environment, but on Linux / Unix just add -lm to the command:
gcc test.c -o test -lm The math library is called libm.so , and the -l command parameter accepts the prefix lib and .a or .so .
You need to link the link to
You need to compile as
gcc test.c -o test -lm gcc (Not g ++) has historically not included math functions by default by default. It was also separated from libc in a separate libm library. To link these functions, you should advise the linker to include the -l library, and then the library name m , thus -lm .
This is probably a linker error. Add the -lm switch to indicate that you want to link to the standard C math library ( libm ), which has a definition for these functions (the header has only a declaration for them - it's worth seeing the difference).
Because you did not tell the linker about the location of the math library. Compile with gcc test.c -o test -lm
You must link the math.h header file with your code. You can do this by typing -lm after your command.
Add title:
#include<math.h>
Note: use abs (), sometimes during evaluation sqrt () can take negative values ββthat cause a domain error.
abs () - provides absolute values;
example, abs (-3) = 3
Include -lm at the end of your command at compile time:
gcc <filename.extension> -lm