2016-09-22 25 views
1

即使我使用math.h頭文件並且使用了雙精度數據,但在C中使用sqrt函數時遇到了問題。當試圖運行下面的代碼:在C中使用sqrt時出現錯誤

#include <stdio.h> 
#include <math.h> 
int main(int argc, char **argv) 
{ 
int J = 1000000; 
sieve(J); 
} 


int sieve(int J) 
{ 
int P[J+1]; P[0] = 0; P[1] = 0; int i; 

for (i = 2; i <= J; i++) //set all values of P to 1 initially 
    { P[i] = 1;} 

int p = 2; 

double y = (double) J; 
double J2 = sqrt(y); 
} 

我receieve錯誤:

/tmp/ccAhS08O.o: In function 'sieve': 
test.c:(.text+0xf8): undefined reference to `sqrt' 
collect2: error: ld returned 1 exit status 
+0

[C的可能的複製 - 未定義引用的sqrt(或其他數學函數)](http://stackoverflow.com/questions/5248919/c-undefined-reference-to-sqrt-or-other-mathematical-functions) –

回答

4

隨着近期所有版本的GCC,你編譯時必須顯式鏈接到數學庫,因爲它不會自動鏈接到標準C庫的其餘部分)。

如果您使用gcc或g ++命令在命令行上進行編譯,您可以通過在命令末尾加上-lm來完成此操作。

例如:gcc的-o FOO的foo.c -lm

或者你可以在Makefile中添加標誌,您使用的編譯

2

您需要數學庫鏈接:-lm

cc -o out main.c -lm 
相關問題