2010-02-02 33 views
1

我有一個工作設置,其中所有文件都在同一個目錄(桌面)。該終端輸出就像這樣:初學者的問題,試圖瞭解鏈接器如何搜索靜態庫

$ gcc -c mymath.c 
$ ar r mymath.a mymath.o 
ar: creating archive mymath.a 
$ ranlib mymath.a 
$ gcc test.c mymath.a -o test 
$ ./test 
Hello World! 
3.14 
1.77 
10.20 

的文件:

mymath.c:

float mysqrt(float n) { 
    return 10.2; 
} 

test.c的:

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

main() { 
    printf("Hello World!\n"); 
    float x = sqrt(M_PI); 
    printf("%3.2f\n", M_PI); 
    printf("%3.2f\n", sqrt(M_PI)); 
    printf("%3.2f\n", mysqrt(M_PI)); 
    return 0; 
} 

現在,我移動存檔MYMATH .a進入子目錄/ temp。我還沒有能夠獲得鏈接工作:

$ gcc test.c mymath.a -o test -l/Users/telliott_admin/Desktop/temp/mymath.a 
i686-apple-darwin10-gcc-4.2.1: mymath.a: No such file or directory 

$ gcc test.c -o test -I/Users/telliott_admin/Desktop/temp -lmymath 
ld: library not found for -lmymath 
collect2: ld returned 1 exit status 

我錯過了什麼?你會推薦哪些資源?

更新:感謝您的幫助。所有答案基本正確。我在博客上寫了here

回答

1

要包含數學庫,請使用-lm,而不是-lmath。此外,您需要在鏈接時使用-L和子目錄來包含庫(-I僅包含用於編譯的頭)。

您可以編譯和鏈接有:

gcc test.c -o test -I/Users/telliott_admin/Desktop/temp /Users/telliott_admin/Desktop/temp/mymath.a 

gcc test.c -o test -I/Users/telliott_admin/Desktop/temp -L/Users/telliott_admin/Desktop/temp -lmymath 

其中mymath.a更名爲libmymath.a。

link text徵求意見(搜索「不好的編程」)使用-l的做法:

+0

對不起,錯字。我正在尋找我自己的「假」圖書館:mymath在/ temp – telliott99 2010-02-02 20:07:47

+0

是的。這些都爲我工作。謝謝。 – telliott99 2010-02-02 20:33:38

2
$ gcc test.c /Users/telliott_admin/Desktop/temp/mymath.a -o test 

編輯:GCC只需要對靜態庫庫的完整路徑。你使用-L來給出一個gcc應該和-l一起搜索的路徑。

1

爲了讓ld找到帶有-l的庫,必須根據模式lib yourname .a來命名。然後你使用-lmymath

所以,沒有辦法讓它把/temp/mymath.a帶到-l。

如果您將它命名爲libmymath.a,那麼-L/temp -lmymath會找到它。