Linker, ELF Sections & MCU Startup File-Embedded C Training in Hyderabad

Need Help or More Information?

Questions about this free C programming course, embedded C training or career guidance? Get in touch.

ARM Cortex-M Programming← PREV_LECNEXT_LEC →

Linker, ELF Sections & MCU Startup File

Understand how the linker places sections in flash and SRAM, what boundaries are needed for .data initialization, and why the startup file is the unsung hero of every bare-metal project.

Pages 301–310Linker & LocatorFlash/SRAM LayoutStartup FileVector Table

1. Relocatable Object Files Revisited

Every .c file compiles to a .o file — a relocatable ELF object. It is “relocatable” because all code and data addresses start at 0. They are placeholders until the linker resolves them. In a program that operates on data, code (.text) and data (.data) work together through load and store instructions.

Compilation Produces Relocatable Objects
main.c
C source code
→
main.o
.text (addr=0)
.data (addr=0)
.bss (size only)
.rodata (addr=0)

The instruction LDR R0, [R1] in .text references a data address in .data. In the .o file, that address is a placeholder. When the linker places .text at 0x08000000 and .data at 0x20000000, it fixes up all such references.

2. The Linker and Locator

The linker does two jobs that are conceptually separate but done together:

  1. Merging sections: Combines all .text sections from every .o file into one big .text output section. Resolves cross-file symbol references (e.g., main.c calling led_init defined in led.c).
  2. Locating (address assignment): Uses the linker script to assign absolute addresses to each output section. This is the “locator” phase.
Linker: Merging .text Sections from Two Object Files
main.o: .text
led.o: .text
main.o: .data
led.o: .data
→
firmware.elf
.text @0x08000000
.data @0x20000000
.bss @0x2000xxxx

3. Flash and SRAM Memory Layout

On the STM32F4 (and most ARM Cortex-M MCUs), there are two main memory regions:

  • Code Memory (FLASH) — starts at 0x08000000. Holds the vector table, .text, .rodata, and the initial values of .data.
  • Data Memory (SRAM) — starts at 0x20000000. Holds .data (at runtime), .bss, stack, and heap.
STM32F4 Memory Layout After Linking
FLASH (0x0800_0000)
0x0800_0000
Vector Table
MSP + handler addresses
.text
code instructions
.rodata
constants, strings
.data (load copy)
initial values
… unused flash …
SRAM (0x2000_0000)
0x2000_0000
.data (runtime)
copied from flash
.bss
zeroed at startup
heap
malloc() area
… unused SRAM …
stack
grows downward ↓

4. Transferring .data from Flash to SRAM

The initial values of global initialized variables are stored in FLASH (in the .data section’s load address). But at runtime, these variables live in SRAM. The startup code is responsible for copying them.

The linker script provides three boundary symbols to make this possible:

  • _sdata — start address of .data in SRAM (VMA)
  • _edata — end address of .data in SRAM
  • _etext — end of .text/.rodata in FLASH = start of .data load copy (LMA)
Boundary Symbols for .data Initialization
FLASH
.text + .rodata
← _etext
.data
(initial values)
memcpy →
SRAM
← _sdata
.data
(runtime values)
← _edata

C — Startup .data/.bss Initialization

/* These symbols are defined in the linker script */
extern uint32_t _sdata;    /* start of .data in SRAM  */
extern uint32_t _edata;    /* end of .data in SRAM    */
extern uint32_t _etext;    /* end of .text = start of .data load copy in FLASH */
extern uint32_t _sbss;     /* start of .bss in SRAM   */
extern uint32_t _ebss;     /* end of .bss in SRAM     */

void init_sections(void)
{
    uint32_t *src, *dst;

    /* 1. Copy .data from FLASH to SRAM */
    src = &_etext;           /* load address in flash */
    dst = &_sdata;           /* runtime address in SRAM */
    while (dst < &_edata) {
        *dst++ = *src++;
    }

    /* 2. Zero-fill .bss in SRAM */
    dst = &_sbss;
    while (dst < &_ebss) {
        *dst++ = 0;
    }
}

Critical: If init_sections() is not called before main(), global initialized variables will have garbage values (leftover flash content), and global uninitialized variables will contain whatever was in SRAM at power-on. This causes mysterious bugs that appear only on fresh power cycles.

5. Importance of the Startup File

The startup file (typically startup.s or startup.c) runs before main(). It is the very first code the CPU executes after reset. Without it, the C runtime environment would be broken — global variables would not be initialized, and main() would run in an undefined state.

The Golden Rule of Startup: Your C code is only safe to run after the startup file has initialized the .data section and zeroed .bss. These C language guarantees are provided by the startup code — not by the compiler or hardware.

Where the Startup File Comes From

  • IDEs (STM32CubeIDE) — provide a device-specific startup file automatically.
  • CMSIS/STM32CubeMX — generates startup_stm32f4xx.s from device templates.
  • Custom bare-metal — you write your own startup.c from scratch (this lecture).

6. What the Startup File Must Do

Task 1: Provide the Vector Table

The vector table must be placed at the start of flash (0x08000000). It holds the initial MSP value and handler addresses. ARM requires this table at a fixed location — the CPU reads it immediately after reset.

C — Minimal Vector Table

#include <stdint.h>

#define SRAM_START  0x20000000UL
#define SRAM_SIZE   (128UL * 1024UL)   /* 128 KB for STM32F407 */
#define SRAM_END    (SRAM_START + SRAM_SIZE)
#define STACK_PTR   SRAM_END           /* stack grows down from top of SRAM */

extern void Reset_Handler(void);
extern void NMI_Handler(void);
extern void HardFault_Handler(void);
extern void SysTick_Handler(void);

/* Vector table — placed in .isr_vector section */
uint32_t vectors[] __attribute__((section(".isr_vector"))) = {
    STACK_PTR,                        /* 0x00: Initial MSP value  */
    (uint32_t) &Reset_Handler,         /* 0x04: Reset              */
    (uint32_t) &NMI_Handler,           /* 0x08: NMI                */
    (uint32_t) &HardFault_Handler,     /* 0x0C: HardFault          */
    /* ... add all 98 entries for STM32F407 ... */
    (uint32_t) &SysTick_Handler,       /* SysTick handler          */
};

Task 2: Reset Handler

C — Reset_Handler

void Reset_Handler(void)
{
    /* Step 1: Copy .data section from flash to SRAM */
    init_sections();

    /* Step 2: Call main() — the C runtime is now ready */
    main();

    /* Step 3: If main() returns (it shouldn't), loop forever */
    for (;;);
}

Default Handler for Unused Interrupts

C — Weak Default Handlers

/* __attribute__((weak)) allows user code to override these */
void __attribute__((weak)) NMI_Handler(void)      { for(;;); }
void __attribute__((weak)) HardFault_Handler(void){ for(;;); }
void __attribute__((weak)) MemManage_Handler(void){ for(;;); }
void __attribute__((weak)) BusFault_Handler(void) { for(;;); }

/* __attribute__((alias)) makes Default_Handler an alias for all
   unused IRQ handlers. If the user defines SysTick_Handler in
   another file, that definition overrides this alias.           */
void Default_Handler(void) { for(;;); }

void __attribute__((weak, alias("Default_Handler"))) TIM2_IRQHandler(void);
void __attribute__((weak, alias("Default_Handler"))) USART2_IRQHandler(void);

weak + alias pattern: This elegant combination means every IRQ defaults to an infinite loop (easy to detect in the debugger) but user code can easily override any specific handler just by defining it — no need to modify the startup file.

7. Programming Exercises

Exercise 1 — Write Your Own Minimal Startup

Create startup.c from scratch for STM32F407. Include only Reset_Handler, NMI_Handler, HardFault_Handler, and SysTick_Handler. Use the weak + alias pattern for all other IRQs.

Exercise 2 — Verify .data Initialization

Add a global variable uint32_t magic = 0xABCD1234. In the debugger, set a breakpoint at the very start of Reset_Handler (before init_sections). Read the value of magic — it should be garbage. Step over init_sections and read again — it should now be 0xABCD1234.

Exercise 3 — Measure Vector Table Size

Calculate how many bytes the STM32F407 vector table occupies in flash. The MCU has 82 IRQs + 15 system exceptions + 1 MSP entry = 98 entries × 4 bytes = 392 bytes. Verify this with arm-none-eabi-objdump -h firmware.elf by looking at the .isr_vector section size.

8. Frequently Asked Questions

Why must the vector table be at address 0x08000000?

On STM32F4, the BOOT pin configuration determines where the CPU looks for the vector table at reset. When BOOT0 is low (normal operation), the flash memory is mapped to address 0x00000000. Since the flash physical address is 0x08000000, both 0x00000000 and 0x08000000 point to the same memory during boot. The CPU reads the initial MSP and Reset_Handler from offset 0 and 4 respectively.

What happens if .bss is not zeroed?

The C standard guarantees that global uninitialized variables are zero-initialized. If the startup code does not zero .bss, this guarantee is violated. You may get non-zero initial values in global variables on power-on (SRAM retains random values after power-up). This causes subtle, intermittent bugs that only appear on power cycles, not resets.

What is the __attribute__((weak)) used for?

A “weak” symbol can be overridden by a “strong” (non-weak) symbol with the same name in another translation unit. In the startup file, all interrupt handlers are defined as weak defaults (usually infinite loops). When you implement, for example, void SysTick_Handler(void) in your own file without the weak attribute, the linker picks your strong definition over the weak default — without you needing to modify the startup file at all.

Quick Knowledge Check

1. Which symbol marks the end of .text in flash (= start of .data load copy)?

  1. _sdata
  2. _edata
  3. _etext
  4. _sbss
Check Answer
Correct answer: C) _etext
_etext marks the end of the .text (+ .rodata) section in flash. The .data initial values are stored immediately after it.

2. The startup code zeroes .bss because…

  1. The compiler inserts zero-clear instructions automatically
  2. SRAM always starts at zero after power-on
  3. The C standard guarantees global uninitialized variables are zero — the startup fulfills this guarantee
  4. .bss variables default to 0xDEADBEEF otherwise
Check Answer
Correct answer: C) The C standard guarantees global uninitialized variables are zero — the startup fulfills this guarantee
The C standard guarantees zero-initialization of globals. SRAM is not automatically zero after power-on — the startup code must do it.

3. How many total entries does the STM32F407 vector table have (MSP + 15 system exceptions + 82 IRQs)?

  1. 64
  2. 82
  3. 98
  4. 128
Check Answer
Correct answer: C) 98
1 MSP + 15 system exceptions + 82 IRQs = 98 entries × 4 bytes = 392 bytes.

EmbeddedPathashala — Embedded Systems Programming on ARM Cortex-M3/M4

Need Help or More Information?

Questions about this free C programming course, embedded C training or career guidance? Get in touch.

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *