5

The following program cannot compile in gcc. But it compiles OK with g++ and MSC++ with .c extension.

#include <math.h>
#include <stdio.h>

int main()
{
  double t = 10;
  double t2 = 200;

  printf("%lf\n", sqrt(t*t2));

  return 0;
}

My system is CentOS, the version info.

> gcc --version
gcc (GCC) 4.1.2 20080704 (Red Hat 4.1.2-46)
Copyright (C) 2006 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

The error info:

> gcc test.c
/tmp/ccyY3Hiw.o: In function `main':
test.c:(.text+0x55): undefined reference to `sqrt'
collect2: ld returned 1 exit status

Is this a bug?

Any one can do a test for me?

Chip Uni
  • 7,454
  • 1
  • 22
  • 29
Yin Zhu
  • 16,980
  • 13
  • 75
  • 117

5 Answers5

18

Have you linked the math library?

gcc -lm test.c -o test 
Tom
  • 43,810
  • 29
  • 138
  • 169
2

Try gcc -lm test.c -o test

For gcc, you need to tell it to link the math library in, by adding -lm to your gcc call.

Prasoon Saurav
  • 91,295
  • 49
  • 239
  • 345
2

Add the math library with flag -lm

> gcc test.c -lm
Drew Dormann
  • 59,987
  • 13
  • 123
  • 180
2

The thing is, gcc -lm test.c -o test won't work because gcc will treat the -lm as a compiler and not a linker option. You need to put the -lm at the end of the command instead, i.e. gcc -o test test.c -lm

user36870
  • 21
  • 1
2

Everybody has been saying this, but I will too. You have to "tell" gcc to link to the math library. When you compile, instead of saying gcc test.c, you have to say gcc -lm test.c. I wish that I could just #include math.h and not have to do anything else.

smilinggoomba
  • 91
  • 1
  • 2
  • 11