Topics / Embedded C / Q13
What happens before main() runs on a microcontroller?
Short answer: On reset, the Cortex-M core reads the initial stack pointer from the first word of the vector table and the reset handler's address from the second word, then starts executing the reset handler. The reset handler (start-up code) typically configures clocks and the FPU (SystemInit), copies the .data section's initial values from flash to RAM, zeroes .bss, runs C/C++ constructors, and finally calls main().
Step by step
- Hardware reset sequence: the core loads
MSPfrom addressVTOR + 0(usually0x00000000, aliased to flash at0x08000000on STM32) andPCfromVTOR + 4. Thumb mode, privileged, all interrupts enabled but no peripheral interrupts enabled yet. - Reset_Handler (in
startup_<device>.sor a C file): -SystemInit(): set up clocks/PLL (or leave that tomain), flash wait states, enable the FPU (SCB->CPACR), setVTORif the image is not at the default address. - Copy.data: from its load address in flash (_sidata) to its run address in RAM (_sdata.._edata). - Zero.bss:_sbss.._ebss. - Optionally copy code into RAM/ITCM (.ramfunc) and initialise other memories (e.g. external SDRAM must be set up before any data placed there is initialised). -__libc_init_array(): runs C++ static constructors and functions marked__attribute__((constructor)). - Callmain(); if it returns, loop forever.
extern uint32_t _sidata, _sdata, _edata, _sbss, _ebss;
extern int main(void);
void SystemInit(void);
void __libc_init_array(void);
void Reset_Handler(void)
{
SystemInit();
for (uint32_t *s = &_sidata, *d = &_sdata; d < &_edata; ) *d++ = *s++;
for (uint32_t *d = &_sbss; d < &_ebss; ) *d++ = 0;
__libc_init_array();
main();
for (;;) { }
}
Things that commonly go wrong
- Writing the reset handler in C is fine, but it must not rely on initialised globals before they are copied, and the compiler may turn the copy loops into
memcpy/memsetcalls (fine if those do not depend on.dataeither). - A watchdog enabled by option bytes can reset the chip during a long
.bssclear on large-RAM parts. - Variables meant to survive a reset must be in a
.noinitsection, or the zeroing wipes them. - Clock configuration done too late can make the copy loops slow on big images.
Follow-up: "What runs before the reset handler?" On many MCUs a boot ROM (system memory bootloader) runs first, reads boot pins/option bytes and decides whether to start user flash, the built-in UART/USB DFU bootloader, or SRAM.