目录
英文原版的-Wl,–gc-sections解释说明如下:
6.3.3.2 Compilation options
The operation of eliminating the unused code and data from the final executable is directly performed by the linker.
In order to do this, it has to work with objects compiled with the following options: -ffunction-sections -fdata-sections.
These options are usable with C and Ada files. They will place respectively each function or data in a separate section in the resulting object file.
Once the objects and static libraries are created with these options, the linker can perform the dead code elimination. You can do this by setting the -Wl,–gc-sections option to gcc command or in the -largs section of gnatmake. This will perform a garbage collection of code and data never referenced.
If the linker performs a partial link (-r linker option), then you will need to provide the entry point using the -e / --entry linker option.
Note that objects compiled without the -ffunction-sections and -fdata-sections options can still be linked with the executable. However, no dead code elimination will be performed on those objects (they will be linked as is).
The GNAT static library is now compiled with -ffunction-sections and -fdata-sections on some platforms. This allows you to eliminate the unused code and data of the GNAT library from your executable.
大致说明如下:
- 在编译C、Ada源文件(C++也可以),在gcc/g++编译选项中增加-ffunction-sections、-fdata-sections,在编译生成的.o目标文件中,会将每个函数或数据段,放在各种单独独立的section中;
- 在链接生成最终可执行文件时,如果带有-Wl,–gc-sections参数,并且之前编译目标文件时带有-ffunction-sections、-fdata-sections参数,则链接器ld不会链接未使用的函数,从而减小可执行文件大小;
- 如果使用了-r的链接参数,来产生重定位的输出,需要显示的调用-e参数来指定程序入口。否则-Wl,–gc-sections不会生效。
使用方式:需要在编译的时候,加入CFLAG += -ffunction-sections, -fdata-sections
选项,在链接的时候,加入LDFLAG += --gc-sections
选项
工作原理:编译的时候,把每个函数作为一个section,每个数据(应该是指全局变量之类的吧)也作为一个section,这样链接的时候,–gc-sections会把没用到的section丢弃掉,最终的可执行文件就只包含用到了的函数和数据。
也就是说,链接的单位,是函数级别,这样就能丢弃没使用的函数。如果不加-ffunction-sections选项,则默认似乎是每个源文件为一个section进行链接,这样子只要这个文件中用到了一个函数,那么所有的函数都会被链接进来。
文章评论