Search code examples
linkerld

How to use ld --gc-sections with OUTPUT_FORMAT(binary)


If my GNU ld linker script has OUTPUT_FORMAT(binary) the ld --gc-sections command-line flag seems to be ignored:

$ cat gcs.c extern void magic(void); void callmagic(void) { magic(); } int uanswer = 42; int main(void) { return 0; } $ cat ofbin.scr OUTPUT_FORMAT(binary) OUTPUT_ARCH(i386) ENTRY(main) SECTIONS { . = 0x10000; .text : { *(.text*) } .data : { *(.data*) *(.rodata*) } .bss : { *(.bss*); } } $ cat ofelf.scr OUTPUT_FORMAT(elf32-i386) OUTPUT_ARCH(i386) ENTRY(main) SECTIONS { . = 0x10000; .text : { *(.text*) } .data : { *(.data*) *(.rodata*) } .bss : { *(.bss*); } } $ gcc -m32 -nostdlib -nostartfiles -nodefaultlibs gcs.c -ffunction-sections -fdata-sections -Wl,--gc-sections,--print-gc-sections -Wl,-T,ofelf.scr /usr/bin/ld: Removing unused section '.text.callmagic' in file '/tmp/ccSFoPYg.o' /usr/bin/ld: Removing unused section '.data.uanswer' in file '/tmp/ccSFoPYg.o' /usr/bin/ld: Removing unused section '.eh_frame' in file '/tmp/ccSFoPYg.o' $ gcc -m32 -nostdlib -nostartfiles -nodefaultlibs gcs.c -ffunction-sections -fdata-sections -Wl,--gc-sections,--print-gc-sections -Wl,-T,ofbin.scr /tmp/cceXCw2b.o: In function `callmagic': gcs.c:(.text.callmagic+0x7): undefined reference to `magic' collect2: error: ld returned 1 exit status

I'm using GNU ld 2.24 and GCC 4.8.4 on Ubuntu 14.04.

How can I make this .c file compile and link with OUTPUT_FORMAT(binary) and with the code of callmagic eliminated by --gc-sections?


Solution

  • It looks like this is impossible, and GNU ld ignores --gc-sections with OUTPUT_FORMAT(binary).

    A possible workaround is using OUTPUT_FORMAT(elf32-i386) and post-processing the output ELF file, e.g. with objcopy -O binary a.out a.out.bin.