2010-05-04 74 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