与静态库链接

Linking with a static library

我在 link 使用我创建的静态库时遇到问题。这是我的目录结构:

test
├── b.c
├── b.o
├── i.h
├── libb.a
└── t
    └── a.c

每个文件的内容如下:

i.h:

#include <stdio.h>
void f (int);
#define LENGTH 4

b.c:

#include "i.h"

void f (int i)
{
    printf ("from b.c: %d\n", i);
}

a.c:

#include "../i.h"

int main (void)
{
    f (23);
    printf ("%d\n", LENGTH);
}

为了构建 b.o,我发布了:gcc -c i.h b.c。为了构建 libb.a,我发布了:ar rcs libb.a b.o.

命令 gcc ../b.o a.c(当从 test/t 内部发出时,会产生 a.out 并按预期运行。问题是当我尝试 link 时 libb.a 使用:gcc -L.. -lb a.c 来自 test/t。link 人抱怨:

$ gcc -L.. -lb a.c
/usr/bin/ld: /tmp/ccbT50MJ.o: in function `main':
a.c:(.text+0xa): undefined reference to `f'
collect2: error: ld returned 1 exit status

请让我知道我在这里遗漏了什么。

你需要把库放在最后(在源文件之后):

gcc -L.. a.c -lb

当在命令行上看到链接器时,链接器只搜索一次库。如果此时没有未定义的符号,则不会再次查看。

来自 ld(1) 文档:

The linker will search an archive only once, at the location where it is specified on the command line. If the archive defines a symbol which was undefined in some object which appeared before the archive on the command line, the linker will include the appropriate file(s) from the archive. However, an undefined symbol in an object appearing later on the command line will not cause the linker to search the archive again.