2010-05-04 76 views
13

编译我们的项目时,我们创建了几个档案(静态库),例如liby.alibz.a,每个档案包含一个定义函数y_function()z_function()的函数的目标文件。然后,这些档案被加入到一个共享对象中,比如​​,这是我们的主要可分配目标之一。如何将共享对象中的所有对象归档?

g++ -fPIC -c -o y.o y.cpp 
ar cr liby.a y.o 
g++ -fPIC -c -o z.o z.cpp 
ar cr libz.a z.o 
g++ -shared -L. -ly -lz -o libyz.so 

当使用该共享对象到示例程序,说x.c,链接失败,因为对功能y_function()z_function()一个未定义的引用。

g++ x.o -L. -lyz -o xyz 

但是,当我将最终的可执行文件直接链接到档案(静态库)时,它可以正常工作。

g++ x.o -L. -ly -lz -o xyz 

我的猜测是,包含在存档的目标文件不链接到共享库,因为他们没有在里面使用。如何强制包容?

编辑:

纳入可使用--whole归档ld选项强制执行。但是,如果编译错误的结果:

g++ -shared '-Wl,--whole-archive' -L. -ly -lz -o libyz.so 
/usr/lib/libc_nonshared.a(elf-init.oS): In function `__libc_csu_init': 
(.text+0x1d): undefined reference to `__init_array_end' 
/usr/bin/ld: /usr/lib/libc_nonshared.a(elf-init.oS): relocation R_X86_64_PC32 against undefined hidden symbol `__init_array_end' can not be used when making a shared object 
/usr/bin/ld: final link failed: Bad value 

任何想法这是从哪里来的?

回答

18

你可以尝试(LD(2)):

--whole-archive 
     For each archive mentioned on the command line after the --whole-archive option, include every object file in the 
     archive in the link, rather than searching the archive for the required object files. This is normally used to turn 
     an archive file into a shared library, forcing every object to be included in the resulting shared library. This 
     option may be used more than once. 

(GCC轮候册, - 全归档)

另外,你应该把-Wl,--no-whole-archive在库列表的末尾。 (正如德米特里尤达科夫在下面的评论中所说)

+0

谢谢,这看起来像我在找什么,但它会产生一个链接错误,我无法确定它来自哪里。我在问题中添加了细节。 – 2010-05-04 09:17:55

+2

'man ld'中有这样一个选项:不要忘记在归档列表后面使用-Wl,-no-whole-archive,因为gcc会将自己的归档列表添加到链接中,并且您可能不会希望这个标志也影响到这些 – 2010-05-04 09:35:17