2010-02-02 34 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会找到它。