問題描述
我需要嚴格優化我的可執行文件的大小(ARM
開發)并且我注意到在我當前的構建方案 (gcc
+ ld
) 中未使用的符號沒有被剝離.
I need to optimize the size of my executable severely (ARM
development) and
I noticed that in my current build scheme (gcc
+ ld
) unused symbols are not getting stripped.
將 arm-strip --strip-unneeded
用于生成的可執行文件/庫不會改變可執行文件的輸出大小 (我不知道為什么,也許是根本不能).
The usage of the arm-strip --strip-unneeded
for the resulting executables / libraries doesn't change the output size of the executable (I have no idea why, maybe it simply can't).
如何(如果存在)修改我的構建管道,以便從生成的文件中刪除未使用的符號?
What would be the way (if it exists) to modify my building pipeline, so that the unused symbols are stripped from the resulting file?
我什至不會想到這一點,但我當前的嵌入式環境不是很強大",而且甚至將 500K
保存在 2M
中,都會帶來非常好的加載性能提升.
I wouldn't even think of this, but my current embedded environment isn't very "powerful" and
saving even 500K
out of 2M
results in a very nice loading performance boost.
更新:
不幸的是,我使用的當前 gcc
版本沒有 -dead-strip
選項和 -ffunction-sections... + --gc
對結果輸出沒有任何顯著差異.ld
的 -sections
Unfortunately the current gcc
version I use doesn't have the -dead-strip
option and the -ffunction-sections... + --gc-sections
for ld
doesn't give any significant difference for the resulting output.
我很震驚這甚至成為一個問題,因為我確信 gcc + ld
應該自動去除未使用的符號(為什么他們甚至必須保留它們?).
I'm shocked that this even became a problem, because I was sure that gcc + ld
should automatically strip unused symbols (why do they even have to keep them?).
推薦答案
對于 GCC,這分兩個階段完成:
For GCC, this is accomplished in two stages:
首先編譯數據,但告訴編譯器將代碼分成翻譯單元內的單獨部分.這將通過使用以下兩個編譯器標志為函數、類和外部變量完成:
First compile the data but tell the compiler to separate the code into separate sections within the translation unit. This will be done for functions, classes, and external variables by using the following two compiler flags:
-fdata-sections -ffunction-sections
使用鏈接器優化標志將翻譯單元鏈接在一起(這會導致鏈接器丟棄未引用的部分):
Link the translation units together using the linker optimization flag (this causes the linker to discard unreferenced sections):
-Wl,--gc-sections
因此,如果您有一個名為 test.cpp 的文件,其中聲明了兩個函數,但其??中一個未使用,您可以使用以下 gcc(g++) 命令省略未使用的那個:
So if you had one file called test.cpp that had two functions declared in it, but one of them was unused, you could omit the unused one with the following command to gcc(g++):
gcc -Os -fdata-sections -ffunction-sections test.cpp -o test -Wl,--gc-sections
(注意 -Os 是一個額外的編譯器標志,它告訴 GCC 優化大小)
(Note that -Os is an additional compiler flag that tells GCC to optimize for size)
這篇關于如何使用 GCC 和 ld 刪除未使用的 C/C++ 符號?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!