#inclu...">

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?

+74
c linker linker-errors libm
May 02 '12 at 6:53
source share
6 answers

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 .

+114
May 2 '12 at 6:55
source share

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 .

+19
May 2 '12 at 6:55
source share

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).

+7
May 2 '12 at 6:55
source share

Because you did not tell the linker about the location of the math library. Compile with gcc test.c -o test -lm

+4
May 02 '12 at 6:56 a.m.
source share

You must link the math.h header file with your code. You can do this by typing -lm after your command.

+3
Mar 15 '17 at 17:55
source share

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

+1
Mar 03 '17 at 5:29
source share



All Articles