3

我试图弄清楚如何使用静态库,但最简单的例子失败了:

//foo.c
int func(int i) {
  return i+1;
}
//main.c
int func(int i);
int main() {
  return func(41);
}

编译foo.cmain.c工作:

gcc -Wall -o foo.o -c foo.c
gcc -Wall -o main.o -c main.c

归档foo.o也不抱怨:

ar rcs libfoo.a foo.o

但链接失败,未定义引用func

ld libfoo.a main.o
ld -L. -lfoo main.o

都给我:

ld: warning: cannot find entry symbol _start; defaulting to 00000000004000b0
main.o: In function `main':
main.c:(.text+0xa): undefined reference to `func'

如果我通过gcc链接绕道而行,我会收到类似的错误:

gcc libfoo.a main.o
gcc -L. -lfoo main.o

给我吗:

main.o: In function `main':
main.c:(.text+0xa): undefined reference to `func'
collect2: ld returned 1 exit status

我在这里做错了什么?根据我阅读/使用的所有手册和搜索引擎,这是使用静态库的方式。


编辑:头脑gcc foo.o main.o工作得很好。

4

1 回答 1

3

在尝试了很多愚蠢的东西之后,最愚蠢的想法是解决方案:ld首先想要目标文件,然后是档案。耶!

gcc libfoo.a main.o  // fails
gcc main.o libfoo.a  // works

-L.如果您使用and指定库也是如此-lfoo:您放置-L的位置显然无关紧要,但您放置的位置-lfoo与您直接指定文件的程度相同.a

于 2011-10-30T14:11:38.230 回答