2009-12-30 8 views
5

El siguiente programa no se puede compilar en gcc. Pero compila OK con g ++ y MSC++ con la extensión .c.a gcc sqrt function bug?

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

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

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

    return 0; 
} 

Mi sistema es CentOS, la información de la versión.

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

La información de error:

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

Es esto un error?

¿Alguien puede hacer una prueba por mí?

+0

Véase también http://stackoverflow.com/questions/1033898 – ephemient

Respuesta

19

¿Ha vinculado la biblioteca matemática?

gcc -lm test.c -o test 
+0

Gracias ... Soy nuevo en este compilador ... Pero g ++ funciona. –

+6

Porque 'g ++' extrae '-lstdC++' que extrae '-lm'. – ephemient

+2

No desea compilar el código C 'sin procesar' con 'g ++'. C y C++ son idiomas diferentes. –

2

Trate gcc -lm test.c -o test

Para gcc, se necesita decir que vincular la biblioteca matemática en, añadiendo -lm a su llamada gcc.

2

Añadir la biblioteca matemática con la bandera -lm

> gcc test.c -lm 
2

Todo el mundo ha estado diciendo esto, pero también lo harán. Tienes que "decirle" a gcc que se vincule a la biblioteca de matemáticas. Cuando compila, en lugar de decir gcc test.c, debe decir gcc -lm test.c. Desearía poder simplemente #include math.h y no tener que hacer nada más.

2

El problema es que gcc -lm test.c -o test no funcionará porque gcc tratará el -lm como un compilador y no como una opción del enlazador. En su lugar, debe poner -lm al final del comando, es decir, gcc -o test test.c -lm

Cuestiones relacionadas