How to decrease the size of generated binaries?

后端 未结 7 1285
谎友^
谎友^ 2021-02-01 05:53

I know that there is an option \"-Os\" to \"Optimize for size\", but it has little affect, or even increase the size on some occasion :(

strip (or \"-s\" option) remov

7条回答
  •  庸人自扰
    2021-02-01 06:28

    You can also use -nostartfiles and/or -nodefaultlibs or the combo of both -nostdlib. In case you don't want a standard start file, you must write your own _start function then. See also this thread (archived) on oompf:

    (quoting Perrin)

    # man syscalls
    # cat phat.cc
    extern "C" void _start() {
            asm("int $0x80" :: "a"(1), "b"(42));
    }
    # g++ -fno-exceptions -Os -c phat.cc
    # objdump -d phat.o
    
    phat.o:     file format elf64-x86-64
    
    Disassembly of section .text:
    
    0000000000000000 <_start>:
       0:   53                      push   %rbx
       1:   b8 01 00 00 00          mov    $0x1,%eax
       6:   bb 2a 00 00 00          mov    $0x2a,%ebx
       b:   cd 80                   int    $0x80
       d:   5b                      pop    %rbx
       e:   c3                      retq
    # ld -nostdlib -nostartfiles phat.o -o phat
    # sstrip phat
    # ls -l phat
    -rwxr-xr-x 1 tbp src 294 2007-04-11 22:47 phat
    # ./phat; echo $?
    42
    

    Summary: Above snippet yielded a binary of 294 bytes, each byte 8 bits.

提交回复
热议问题