C中的分层链接

我想以分层方式链接三个文件。

// ac int fun1(){...} int fun2(){...} // bc extern int parameter; int fun3(){...//using parameter here} // main.c int parameter = 1; int main(){...// use fun1 fun2 fun3} 

所以,我首先将三个文件分别编译到目标文件aobomain.o 。 然后我想将aobo组合成另一个目标文件tools.o 。 最后使用tools.omain.o生成可执行文件。

但是,当我尝试将aobo结合起来像ld -o tools.o ao bo ,链接器会显示undefined reference to 'parameter' 。 我怎么能将这些目标文件链接到一个中间目标文件?

您希望-r选项生成可重定位目标文件(想想’可重用’):

 ld -o tools.o -r ao bo 

工作代码

abmain.h

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

AC

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

公元前

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

main.c中

 #include  #include "abmain.h" int parameter = 1; int main(void){fun1();fun3();fun2();fun3();return 0;} 

编译和执行

 $ gcc -Wall -Wextra -c ac $ gcc -Wall -Wextra -c bc $ gcc -Wall -Wextra -c main.c $ ld -r -o tools.o ao bo $ 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加载程序等)进行了validation。 但是,至少从第7版Unix (大约1978年)开始, -r选项已经在主流Unix上的ld命令中,所以它很可能适用于大多数基于Unix的编译系统,即使它是其中之一广泛使用的选项。