2012-04-12 44 views
9

編譯/鏈接到-nostdlib似乎可以防止靜態初始化,即使我將自己的crti.s和crtn.s與.init/.fini部分相加。g ++,靜態初始化和-nostdlib

有沒有解決方法可以使g ++生成插入.init或我可以手動調用的靜態初始化代碼?

這是我的嘗試:

g++ -o test.o -c -fno-use-cxa-atexit test.cc # has _start (entry point) 
               # that calls _init and _main 
as -o crti.o crti.s  # has _init in section .init 
as -o crtn.o crtn.s 
g++ -o test ./crti.o test.o -nodefaultlibs -nostartfiles ./crtn.o 

-nodefaultlibs單獨包括靜態初始化代碼和電話,但部隊使用的libc-_start/_init的。

-nodefaultlibs -nostartfiles允許我使用自己的_start/_init,但不包含代碼或調用靜態初始化。

+0

試試這個'G ++ -o測試./crti.o ./crtn.o test.o輪候冊,-nodefaultlibs -nostartfiles'與看到您的使用,我覺得你只希望你的啓動文件被包含在內,並且你似乎可以使用標準庫中的其他庫文件? – 2012-04-12 08:56:37

+0

@Pavan:我試過'-Wl,-nodefaultlibs -Wl,-nostartfiles',但是然後libc-_init被編譯器包含。用法適用於IBM Cell SPU - 我需要自己的啓動代碼來設置所有內容,並且不使用libc函數,但仍需要靜態構造函數才能調用。 – Thomas 2012-04-12 09:06:51

+0

我不熟悉C++,所以我不明白你的意思,但仍然需要靜態構造函數來調用「?你能告訴我一些例子嗎?我一直在想靜態庫。 – 2012-04-12 09:19:10

回答

9

gcc linker docs

-nostdlib

不要使用標準系統啓動文件或庫時 鏈接。 指定系統的聯動 庫,如-static-libgcc中或-shared-libgcc中沒有啓動文件,只有你指定將 傳遞給鏈接庫和選項,將被忽略。

因此使用,

-nodefaultlibs

鏈接時不要使用標準系統庫。 只有指定的庫將傳遞給鏈接器,指定系統庫鏈接的選項(如-static-libgcc或-shared-libgcc)將被忽略。 標準啓動文件正常使用,除非使用-nostartfiles。編譯器可以生成對memcmp,memset,memcpy和memmove的調用。這些條目通常由libc中的條目解決。當指定此選項時,應通過其他一些機制提供這些入口點。

也可以嘗試,

g++ -Wl, -static 

-Wl  passes the next command on to the linker 
-static On systems that support dynamic linking, this prevents linking with 
     the shared libraries. On other systems, this option has no effect. 
+0

這幫了很多,謝謝。 – Thomas 2012-04-12 08:14:46

+0

使用-nodefaultlibs包含並調用了靜態初始化的代碼,但後來我看不到使用我自己的.init/_start代碼的方法。這仍然是可能的嗎? – Thomas 2012-04-12 08:37:44

+0

你使用過'-nostartfiles'嗎? – 2012-04-12 08:38:09