2012-03-20 115 views
2

下面這個簡單的程序不會因爲某些原因而構建。它說「未定義的pow參考」,但包含數學模塊,我用-lm標誌構建它。如果我使用像pow這樣的pow(2.0,4.0),它會生成,所以我懷疑我的類型轉換有問題。ANSI-C pow功能和類型鑄造

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

int main() { 
    int i; 

    for (i = 0; i < 10; i++) { 
     printf("2 to the power of %d = %f\n", i, pow(2.0, (double)i)); 
    } 

    return EXIT_SUCCESS; 
} 

這裏是bulid日誌:

**** Build of configuration Debug for project hello **** 
make all 
Building file: ../src/hello.c 
Invoking: GCC C Compiler 
gcc -O0 -g -pedantic -Wall -c -lm -ansi -MMD -MP -MF"src/hello.d" -MT"src/hello.d" -o "src/hello.o" "../src/hello.c" 
Finished building: ../src/hello.c 

Building target: hello 
Invoking: GCC C Linker 
gcc -o "hello" ./src/hello.o 
./src/hello.o: In function `main': 
/home/my/workspace/hello/Debug/../src/hello.c:19: undefined reference to `pow' 
collect2: ld returned 1 exit status 
make: *** [hello] Error 1 

**** Build Finished **** 

回答

3

你告訴它使用數學庫在錯誤的地方 - 你指定的數學庫編譯時(在那裏贏得沒有幫助),但在鏈接時(實際需要的地方)將它排除在外。您需要在鏈接時指定它:

gcc -o "hello" ./src/hello.o -lm 
+2

傑裏的說法是,您沒有在鏈接階段傳遞它。請參閱'Invoking:GCC C Linker'後面的行。也許你可以發佈你的Makefile? – 2012-03-20 14:52:39

+0

謝謝K.G.我正在使用Eclipse,因此我沒有將-lm參數添加到GCC C鏈接器設置中,而是添加到了GCC C編譯器設置中。在鏈接階段傳遞它解決了這個問題。 – pocoa 2012-03-20 14:56:19