2009-12-30 62 views
5

以下程序無法在gcc中編譯。但它用g ++和MSC++以.c擴展名編譯OK。一個gcc sqrt函數的bug?

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

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

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

    return 0; 
} 

我的系統是CentOS,版本信息。

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

錯誤信息:

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

這是一個錯誤?

任何人都可以爲我做一個測試?

+0

另請參見http://stackoverflow.com/questions/1033898 – ephemient 2009-12-31 23:41:34

回答

19

你鏈接了數學庫嗎?

gcc -lm test.c -o test 
+0

謝謝......我是這個編譯器的新手..但g ++的作品。 – 2009-12-30 17:21:14

+6

因爲'g ++'拉入'-lstdC++',它拉入'-lm'。 – ephemient 2009-12-30 17:55:33

+2

你不想用'g ++'編譯'raw'C代碼。 C和C++是不同的語言。 – 2009-12-31 06:35:26

2

嘗試gcc -lm test.c -o test

對於GCC,你需要告訴它的數學庫中加入-lm 您電話的gcc鏈接。

2

添加數學庫標誌-lm

> gcc test.c -lm 
2

大家一直說這一點,但我也不能免俗。你必須「告訴」gcc鏈接到數學庫。當你編譯時,而不是說gcc test.c,你必須說gcc -lm test.c。我希望我可以只用#include math.h而不必做任何事情。

2

事情是,gcc -lm test.c -o test將不起作用,因爲gcc會將-lm視爲編譯器而不是鏈接器選項。您需要將-lm放在命令的末尾,例如gcc -o test test.c -lm