Home / Learn Chip Programming / Startup Code and the Reset Handler

Startup Code and the Reset Handler

What runs before main(): vector table, stack pointer, data init, clock setup.

In shortWhat runs before main(): vector table, stack pointer, data init, clock setup.

Theory in plain words

Boot sequencePower on / resetLoad SP and PC from vector tableReset_Handlercopy .data, zero .bssSystemInit (clock)main()
Boot sequence

What it is

On reset a Cortex-M loads the stack pointer from address 0 and jumps to the reset handler from address 4. The handler initialises RAM, calls SystemInit and then main().

Why we use it

Understanding startup explains hard faults at boot, wrong clocks, global constructors and bootloader jumps.

How it works

Vector table in flash: [initial SP, Reset_Handler, NMI, HardFault, ...]. Reset_Handler copies .data, zeroes .bss, runs init, calls main.

Where it is used

  • Porting to a new chip
  • Writing a bootloader
  • Debugging "device does not start"

Step through the boot

Simulated reset sequenceTry it Yourself

If the chip hangs before main(), the cause is usually in this chain: bad linker script, missing vector table or wrong clock.

Reset handler in C
extern uint32_t _sidata, _sdata, _edata, _sbss, _ebss, _estack;
void Reset_Handler(void) {
    uint32_t *src = &_sidata, *dst = &_sdata;
    while (dst < &_edata) *dst++ = *src++;      // copy .data
    for (dst = &_sbss; dst < &_ebss; ) *dst++ = 0;   // zero .bss
    SystemInit();
    main();
    while (1) {}
}
__attribute__((section(".isr_vector"))) void (*const vectors[])(void) = {
    (void (*)(void))&_estack, Reset_Handler, NMI_Handler, HardFault_Handler };

Quick quiz

1. Where does Cortex-M find the start address?

2. Zeroing .bss is done by...