Gcc sqrt error?

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

#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, version information.

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

Error Information:

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

This is mistake?

Can anyone do a test for me?

+5
source share
5 answers

Have you linked the math library?

gcc -lm test.c -o test 
+19
source

Try gcc -lm test.c -o test

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

+2
source

-lm

> gcc test.c -lm
+2

, . "" gcc, . , gcc test.c, gcc -lm test.c. , #include math.h .

+2
source

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

+2
source

All Articles