Keep a section from being discarded with KEEP() in a linker script
Stop --gc-sections from deleting an interrupt vector table nothing references by wrapping its input section in KEEP() in a GNU ld linker script.
-Wl,--gc-sections removes input sections that no symbol reaches, and a vector table is exactly that: the hardware reads it, and no code refers to it. __attribute__((used)) keeps the compiler from dropping the array, but it does not tell the linker anything. [KEEP()](https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html) does.
MEMORY { FLASH (rx) : ORIGIN = 0x08000000, LENGTH = 64K }
SECTIONS {
.isr_vector : { KEEP(*(.isr_vector)) } > FLASH
.text : { *(.text*) } > FLASH
}__attribute__((section(".isr_vector"), used))
const unsigned int vectors[2] = { 0x20005000u, 0x08000101u };
void Reset_Handler(void) { for (;;) { } }arm-none-eabi-gcc -mcpu=cortex-m3 -mthumb -nostdlib -ffunction-sections -fdata-sections \
-Wl,--gc-sections -Wl,-e,Reset_Handler -T link.ld vec.c -o vec.elf
arm-none-eabi-nm vec.elf | grep vectors08000000 R vectorsRemove the KEEP() and the grep prints nothing, because the section was collected and the symbol went with it. The firmware then links without complaint and the board does not boot.
Because the section name is matched by the pattern, one KEEP covers every file that defines it. Do the same for .init_array, .fini_array and any registry table filled by __attribute__((section)), since all of them are reached only through boundary symbols. Linking with --print-gc-sections shows what was removed.