Write a Startup File in C Instead of Assembly for Cortex-M
Replace the vendor assembly startup file with one C file for a Cortex-M4: vector table, weak aliases, data copy, bss clear and the GCC flags that keep it safe.

The startup_stm32f407xx.s file that ships with every STM32 project is about 200 lines of assembly, and what it does fits in a page of C. Writing the startup in C gives you a file that compiles with the rest of the project, shows up in a debugger with line numbers, and can use your own types and constants. The cost is a small set of rules about what the compiler may assume while the runtime is not yet set up. This post builds a complete startup file in C for a Cortex-M4 (STM32F407 as the target) using arm-none-eabi-gcc 13.2, and states the rules that keep it correct.
What the assembly file does
A vendor startup file does five jobs, and the C version must do the same five:
Put the initial stack pointer and handler addresses in the vector table.
Provide a weak default for every handler, so an unwritten handler still has an address.
Run the reset handler: copy
.data, clear.bss.Call
SystemInit()and the C library's initialisation (__libc_init_array).Call
main, with a catch for a return.
Nothing in that list needs an instruction C cannot produce, with one exception that matters on some parts: setting the stack pointer. On a Cortex-M the core loads SP from table entry 0 before the first instruction, so C does not have to. On Cortex-M0 parts used with a boot loader, or when software jumps to an application, SP must be set by code, and that needs a tiny piece of inline assembly (shown later).
The linker symbols
The C file gets its addresses from the linker script. These are the names used by the CMSIS-style script that STM32CubeIDE generates, and by the example below:
#ifndef STARTUP_H
#define STARTUP_H
#include <stdint.h>
extern uint32_t _estack; /* top of RAM */
extern uint32_t _sidata; /* flash address of .data initial values */
extern uint32_t _sdata; /* RAM start of .data */
extern uint32_t _edata; /* RAM end of .data */
extern uint32_t _sbss; /* RAM start of .bss */
extern uint32_t _ebss; /* RAM end of .bss */
#endifThey are declared as uint32_t so that pointer arithmetic steps in words, which matches the linker script aligning each section to 4 bytes. The values of these symbols are meaningless. What matters is their addresses, so the code writes &_sdata.
The startup file
#include <stdint.h>
#include "startup.h"
extern int main(void);
extern void SystemInit(void);
extern void __libc_init_array(void);
void Reset_Handler(void);
void Default_Handler(void);
#define WEAK_HANDLER(name) \
void name(void) __attribute__((weak, alias("Default_Handler")))
WEAK_HANDLER(NMI_Handler);
WEAK_HANDLER(HardFault_Handler);
WEAK_HANDLER(MemManage_Handler);
WEAK_HANDLER(BusFault_Handler);
WEAK_HANDLER(UsageFault_Handler);
WEAK_HANDLER(SVC_Handler);
WEAK_HANDLER(DebugMon_Handler);
WEAK_HANDLER(PendSV_Handler);
WEAK_HANDLER(SysTick_Handler);
WEAK_HANDLER(WWDG_IRQHandler);
__attribute__((section(".isr_vector"), used))
void (*const vector_table[])(void) = {
(void (*)(void))(&_estack),
Reset_Handler,
NMI_Handler,
HardFault_Handler,
MemManage_Handler,
BusFault_Handler,
UsageFault_Handler,
0, 0, 0, 0,
SVC_Handler,
DebugMon_Handler,
0,
PendSV_Handler,
SysTick_Handler,
WWDG_IRQHandler,
};
__attribute__((noreturn, optimize("no-tree-loop-distribute-patterns")))
void Reset_Handler(void)
{
uint32_t *src = &_sidata;
uint32_t *dst = &_sdata;
while (dst < &_edata)
*dst++ = *src++;
for (dst = &_sbss; dst < &_ebss; )
*dst++ = 0;
SystemInit();
__libc_init_array();
main();
for (;;)
;
}
void Default_Handler(void)
{
for (;;)
;
}The macro WEAK_HANDLER declares a function as a weak alias for Default_Handler. A weak definition is used only if no strong definition of the same name exists in the link. When your application defines void SysTick_Handler(void), the linker picks it and the alias disappears from the table. The post on weak symbols covers how the alias resolves.
The table element type is void (*const)(void). The first slot needs a cast of the stack-top address to a function pointer type, which is the usual trick: GCC accepts it, and the value is the same word. Function addresses carry bit 0 set automatically.
The traps
Four rules apply to code that runs before .data is copied and .bss is cleared.
No global state before the copy. The copy loops use only locals and linker symbols. If you add a call to a function that reads a global, the global may not have its initial value yet. Calling SystemInit() after the copy is safe, and CMSIS's own SystemInit writes only to peripheral registers and SCB->VTOR. Do not move it before the copy unless you know it touches no globals.
**The compiler may turn the clear loop into a memset call.** GCC recognises "store zero in a loop" and, at -O2 or higher (and at -Os on some versions), rewrites it into a call to memset. That call goes to newlib's memset, which is a normal function that may rely on an initialised C environment, and it can even recurse: if memset itself is built from a similar loop, the call lands in the function that is supposed to be clearing memory. The fix is the optimize("no-tree-loop-distribute-patterns") attribute on the reset handler, as in the listing above, or -fno-tree-loop-distribute-patterns for the whole file. The GCC manual documents both. Note that -ffreestanding does not remove the problem: the manual says that GCC may emit calls to memcpy, memmove, memset and memcmp even in freestanding mode, so a freestanding program must provide them.
**naked limits the body.** The naked attribute removes the prologue and epilogue, and the GCC manual says that only basic asm statements can safely be included in a naked function. The listing above therefore leaves naked out and relies on the core having set SP from the table. For the cases where SP is not guaranteed, write the reset handler in two layers:
__attribute__((naked, noreturn))
void Reset_Handler(void)
{
__asm (
"ldr r0, =_estack\n\t"
"mov sp, r0\n\t"
"bl reset_main\n\t"
);
}
void reset_main(void)
{
/* copy .data, clear .bss, SystemInit, __libc_init_array, main */
}The assembly sets the stack pointer, then branches to an ordinary C function. For a normal Cortex-M4 reset the first layer is unnecessary, and the best choice is to leave naked out of the single function.
**__libc_init_array and C++.** This function runs the .preinit_array, .init_array and _init entries that newlib provides. A C-only firmware with no constructors works without it, but static constructors in C++ code and functions marked __attribute__((constructor)) need it. The linker script must also keep those sections, covered in a post of its own.
Building it
The compile and link lines show where the choices land:
arm-none-eabi-gcc -mcpu=cortex-m4 -mthumb -Os -g -ffreestanding \
-fno-tree-loop-distribute-patterns -ffunction-sections -fdata-sections -c startup.c -o startup.o
arm-none-eabi-gcc -mcpu=cortex-m4 -mthumb --specs=nano.specs \
-Wl,-T,link.ld -Wl,--gc-sections startup.o main.o -o firmware.elf-ffreestanding tells the compiler not to assume a hosted C environment, and -fno-tree-loop-distribute-patterns is the flag that stops the memset rewrite. --specs=nano.specs selects newlib-nano and its smaller printf.
Checking the result
Disassemble the reset handler to confirm no memset call sneaked in:
arm-none-eabi-objdump -d startup.o | grep -A40 '<Reset_Handler>' | grep bl 2a: f7ff fffe bl 0 <SystemInit>
2e: f7ff fffe bl 0 <__libc_init_array>
32: f7ff fffe bl 0 <main>Three bl lines, for SystemInit, __libc_init_array and main, and nothing for memset or memcpy. The offsets vary by build. Relocation entries are zeros in an object file because the linker fills them.
When to keep the assembly file
Keep the vendor file if you rely on tools that parse it (some IDE importers), if you target a part where the vendor has a quirk in the early code (certain parts need a clock or a watchdog disabled before the copy loops), or if the project must pass a certification audit that reviews unchanged vendor files. For everything else, C is the better source form.
A debugging habit worth keeping
A startup file in C has one advantage the assembly version lacks: you can set a breakpoint on a line of it and step. Stop at Reset_Handler after a reset and step through the copy loop with the debugger watching dst. When a project misbehaves only after reset and not after a debugger-driven load, the usual cause is that the debugger's load script sets registers or copies data that the real startup does not. Stepping the real handler on a hardware reset (monitor reset halt, then continue to a breakpoint at main) removes that difference and shows whether the loops finish. If main is reached with dst equal to &_edata, the copy completed; if the core faults inside the loop, one of the linker symbols points outside RAM.


