Skip to content
systemcoding.dev
Embedded

Define a minimal Cortex-M vector table array in C

Build the Cortex-M vector table as a const array of function pointers in C, placed in its own section, with the stack top in slot 0 and Reset in slot 1.

2 min read
Summarize in AI

A Cortex-M core reads its initial stack pointer from word 0 of the vector table and its first instruction address from word 1, so the table is just an array of words at the start of flash. In C that is a const array of function pointers, with the stack top cast to fit, put in a named section the linker script places first. This example targets a Cortex-M4 and the Arm GNU Toolchain 13.3.Rel1 (GCC 13.3).

vectors.cc
extern unsigned long _estack;
void Reset_Handler(void);
void Default_Handler(void);

void NMI_Handler(void)        __attribute__((weak, alias("Default_Handler")));
void HardFault_Handler(void)  __attribute__((weak, alias("Default_Handler")));
void SVC_Handler(void)        __attribute__((weak, alias("Default_Handler")));
void PendSV_Handler(void)     __attribute__((weak, alias("Default_Handler")));
void SysTick_Handler(void)    __attribute__((weak, alias("Default_Handler")));

__attribute__((section(".isr_vector"), used))
void (* const vector_table[])(void) = {
    (void (*)(void))&_estack,  /* 0: initial MSP */
    Reset_Handler,             /* 1 */
    NMI_Handler,               /* 2 */
    HardFault_Handler,         /* 3 */
    0, 0, 0, 0, 0, 0, 0,       /* 4-10: MemManage, BusFault, UsageFault, reserved */
    SVC_Handler,               /* 11 */
    0, 0,                      /* 12-13: DebugMon, reserved */
    PendSV_Handler,            /* 14 */
    SysTick_Handler,           /* 15 */
};

The weak alias gives every handler a default body, so a real SysTick_Handler in another file replaces it without touching the table. The used attribute stops the compiler discarding an array nothing references. Vendor interrupts follow slot 15 in the order of the chip's reference manual. The linker script still has to keep and place this section, which the KEEP snippet covers.

Also inToolchains
Taggedccortex m
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.