为什么编译器版本出现在我的ELF可执行文件中?

Dev*_*oot 14 c linux gcc elf

我最近使用gcc在Debian Linux下编译了一个简单的hello world C程序:

gcc -mtune=native -march=native -m32 -s -Wunused -O2 -o hello hello.c
Run Code Online (Sandbox Code Playgroud)

文件大小为2980字节.我在十六进制编辑器中打开它,我看到以下几行:

GCC: (Debian 4.4.5-8) 4.4.5 GCC: (Debian 4.4.5-10) 4.4.5 .shstrtab .interp .note.ABI-tag .note.gnu.build-id .gnu.hash .dynsym .dynstr .gnu.version .gnu.version_r .rel.dyn .rel.plt .init .text .fini .rodata .eh_frame .ctors .dtors .jcr .dynamic .got .got.plt data.data .bss .comment
Run Code Online (Sandbox Code Playgroud)

他们真的需要吗?无法减少可执行文件的大小?

Mat*_*Mat 9

那是在ELF二进制文件的注释部分.你可以剥掉它:

$ gcc -m32 -O2 -s -o t t.c
$ ls -l t
-rwxr-xr-x 1 me users 5488 Jun  7 11:58 t
$ readelf -p .comment t

String dump of section '.comment':
  [     0]  GCC: (Gentoo 4.5.1-r1 p1.4, pie-0.4.5) 4.5.1
  [    2d]  GCC: (Gentoo 4.5.2 p1.1, pie-0.4.5) 4.5.2


$ strip -R .comment t


$ readelf -p .comment t
readelf: Warning: Section '.comment' was not dumped because it does not exist!
$ ls -l t
-rwxr-xr-x 1 me users 5352 Jun  7 11:58 t
Run Code Online (Sandbox Code Playgroud)

虽然收益很小,但不确定是否值得.


小智 9

使用-Qn来避免这种情况.

aa$ touch hello.c
aa$ gcc -c hello.c 
aa$ objdump -s hello.o 

hello.o:     file format elf32-i386

Contents of section .comment:
 0000 00474343 3a202844 65626961 6e20342e  .GCC: (Debian 4.
 0010 372e322d 35292034 2e372e32 00        7.2-5) 4.7.2.   
aa$ gcc -Qn -c hello.c 
aa$ objdump -s hello.o 

hello.o:     file format elf32-i386

aa$ gcc -v 
Using built-in specs.
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=/usr/lib/gcc/i486-linux-gnu/4.7/lto-wrapper
Target: i486-linux-gnu
Configured with: ../src/configure -v --with-pkgversion='Debian 4.7.2-5' --with-bugurl=file:///usr/share/doc/gcc-4.7/README.Bugs --enable-languages=c,c++,go,fortran,objc,obj-c++ --prefix=/usr --program-suffix=-4.7 --enable-shared --enable-linker-build-id --with-system-zlib --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --with-gxx-include-dir=/usr/include/c++/4.7 --libdir=/usr/lib --enable-nls --with-sysroot=/ --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --enable-gnu-unique-object --enable-plugin --enable-objc-gc --enable-targets=all --with-arch-32=i586 --with-tune=generic --enable-checking=release --build=i486-linux-gnu --host=i486-linux-gnu --target=i486-linux-gnu
Thread model: posix
gcc version 4.7.2 (Debian 4.7.2-5) 
aa$ 
Run Code Online (Sandbox Code Playgroud)


APr*_*mer 5

这是在一个没有加载到内存中的注释部分(并注意ELF文件通常使用填充,以便内存映射它们将保持正确的对齐).如果你想摆脱这些不需要的部分,请参阅各种objcopy选项并找出:

objcopy --remove-section .comment a.o b.o
Run Code Online (Sandbox Code Playgroud)