Skip to content
systemcoding.dev
Toolchains

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.

1 min read
Summarize in AI

-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.

link.ldld
MEMORY { FLASH (rx) : ORIGIN = 0x08000000, LENGTH = 64K }

SECTIONS {
    .isr_vector : { KEEP(*(.isr_vector)) } > FLASH
    .text       : { *(.text*) } > FLASH
}
vec.cc
__attribute__((section(".isr_vector"), used))
const unsigned int vectors[2] = { 0x20005000u, 0x08000101u };

void Reset_Handler(void) { for (;;) { } }
Shell
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 vectors
Text
08000000 R vectors

Remove 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.

Also inEmbedded
Share

More snippets

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.