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

Ant's picture Ant's · May 2, 2012 · Viewed 220.1k times · Source

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?

Answer

wallyk picture wallyk · May 2, 2012

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.