Why am I getting "undefined reference to sqrt" error even though I include math.h header?

c, libm, linker, linker-errors

Solution

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.

Problem

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?

Original source

Related problems