编译静态库时出现问题

时间:2014-03-25 01:31:38

标签: c linux gcc linker ar

我创建了一个静态库libstuff.agccar。我在/custom/lib/dir/中安装了库,在/custom/include/dir/中安装了头文件。当我尝试针对存档编译另一个应用程序时,我遇到了问题。

我尝试编译的应用程序基本上使用gcc -L/custom/lib/dir/ -I/custom/include/dir/ -lstuff

当我尝试编译时,我收到有关我在stuff.h中声明的函数的错误,并在stuff.c中定义。

main.c:51: undefined reference to `stuff_init'
collect2: error: ld returned 1 exit status

如果我从libstuff.a删除/custom/lib/dir/,编译器会抱怨/usr/bin/ld: cannot find -lstuff。如果我把它放回去,它不会抱怨。所以它正确地找到档案。

如果我从#include "stuff.h" gcc删除代码行main.c抱怨stuff_init未定义,那么它就是正确找到标题。

如果我运行nm libstuff.a,则输出包含0000000000000000 T stuff_init。因此,该功能在存档文件中定义。

那么我做错了什么?

1 个答案:

答案 0 :(得分:5)

您没有显示确切的链接行,但您可能应该(但不要)在目标文件之后列出库:

gcc -o program main.o -L/custom/lib/dir -lstuff

如果库外有多个目标文件,则在任何库之前列出它们。 -L选项可以在使用给定目录中的库的-llib选项之前的任何位置。