我试图弄清楚如何使用静态库,但最简单的例子失败了:
//foo.c
int func(int i) {
return i+1;
}
//main.c
int func(int i);
int main() {
return func(41);
}
编译foo.c
和main.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
工作得很好。