Why main() Is Not the First Code That Runs

Your program starts before main().
Hardware resets.
Startup code prepares the system.

1. The Reset Event

When an embedded system powers on or resets, the processor does not immediately jump to main().

Instead, the CPU begins execution from a fixed memory address defined by the architecture.

This address typically points to the reset vector, which contains the starting location of the program.

The reset handler becomes the first piece of firmware that runs.

2. The Startup Code

Before main() executes, the system must prepare the runtime environment.

This initialization is performed by startup code, which is usually written in low-level assembly or minimal C.

Typical tasks include:
  • setting the stack pointer
  • initializing memory sections
  • configuring the data and BSS segments
  • preparing the runtime environment

Without these steps, the program cannot safely execute normal C code.

3. Memory Initialization

Two important memory sections must be prepared before main() runs.

Initialized data
Variables with predefined values are copied from non-volatile memory (Flash) into RAM.

Uninitialized data (BSS)
Variables without explicit values are cleared and set to zero.

This ensures that global and static variables behave according to the language rules.

4. Hardware Preparation

In many embedded systems, the startup code may also perform early hardware setup.

This can include:
  • configuring system clocks
  • setting up interrupt vectors
  • initializing essential peripherals

Only after these steps does the system call main().

5. Why This Matters for Firmware Engineers

Understanding startup behavior is essential when working with:
  • bootloaders
  • linker scripts
  • interrupt vector tables
  • low-level debugging

Many system issues occur before main() executes, especially when initialization code or memory configuration is incorrect.

Firmware engineers must often inspect startup code when diagnosing early boot failures.
main() begins your application.
Startup code makes the system ready to run it.