C语言中的层次链接

3
我想以层次方式链接三个文件。
// a.c
int fun1(){...}
int fun2(){...}

// b.c
extern int parameter;
int fun3(){...//using parameter here}

// main.c
int parameter = 1;
int main(){...// use fun1 fun2 fun3}

所以,我先将三个文件分别编译成目标文件a.ob.omain.o。然后我想将a.ob.o合并到另一个目标文件tools.o中。最终使用tools.omain.o生成可执行文件。
但是,当我尝试像ld -o tools.o a.o b.o这样合并a.ob.o时,链接器会提示undefined reference to 'parameter'。我该如何将这些目标文件链接到一个中间目标文件中?
1个回答

7
您需要使用-r选项来生成可重定位的目标文件(即“可重用”)。
ld -o tools.o -r a.o b.o

工作代码

abmain.h

extern void fun1(void);
extern void fun2(void);
extern void fun3(void);
extern int parameter;

a.c

#include <stdio.h>
#include "abmain.h"
void fun1(void){printf("%s\n", __func__);}
void fun2(void){printf("%s\n", __func__);}

b.c

#include <stdio.h>
#include "abmain.h"
void fun3(void){printf("%s (%d)\n", __func__, ++parameter);}

main.c

#include <stdio.h>
#include "abmain.h"

int parameter = 1;
int main(void){fun1();fun3();fun2();fun3();return 0;}

编译和执行

$ gcc -Wall -Wextra -c a.c
$ gcc -Wall -Wextra -c b.c
$ gcc -Wall -Wextra -c main.c
$ ld -r -o tools.o a.o b.o
$ gcc -o abmain main.o tools.o
$ ./abmain
fun1
fun3 (2)
fun2
fun3 (3)
$

在 Mac OS X 10.11.6 环境下,使用 GCC 6.1.0 进行验证(以及 XCode 7.3.0 载入器等)。但是,-r选项自第七版Unix(大约在1978年左右)以来就已经在主流Unix的ld命令中出现,因此它可能在大多数基于Unix的编译系统中都可用,即使它是其中未被广泛使用的选项之一。


谢谢!这正是我想要的。 - Van

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接