Skip to content
systemcoding.dev
Embedded

Write a GNU ld Linker Script for an STM32 From Scratch

Write a complete GNU ld linker script for an STM32F407: MEMORY regions, vector table, .text, .data with AT>, .bss, heap and stack reserve, and link-time checks.

6 min read
Summarize in AI
Flat illustration of source code passing through a compiler and linker into a binary, with the GNU, STMicroelectronics and Arm logos.

The linker script is the file that turns object files into a firmware image at the right addresses. Every STM32 project has one, and most developers copy the vendor's without reading it, which works until a section lands in the wrong region or the stack silently collides with the heap. This post writes a complete script for the STM32F407VG from nothing, one block at a time, using GNU ld from binutils 2.42 (the one in the Arm GNU Toolchain 13.2). The goal is that you can read any other vendor script afterwards and know what each line is for.

The target has 1 MiB of flash at 0x08000000, 128 KiB of SRAM1 and SRAM2 at 0x20000000, and 64 KiB of core-coupled memory (CCM) at 0x10000000, per the STM32F407 datasheet and reference manual RM0090. The CCM cannot be reached by DMA, so this script leaves it for a later post.

Step 1: describe the memory

MEMORY declares the regions the linker may fill:

Text
MEMORY
{
  FLASH (rx)  : ORIGIN = 0x08000000, LENGTH = 1024K
  RAM   (rwx) : ORIGIN = 0x20000000, LENGTH = 128K
}

The letters after each name are attributes: r readable, w writable, x executable. They steer the linker's choice for orphan sections (sections your script does not mention) but do not set hardware permissions. The linker errors out when the contents of a region exceed its LENGTH, which is the cheapest overflow check you will get: region 'FLASH' overflowed by 312 bytes.

Step 2: symbols and entry point

Two definitions come before SECTIONS:

Text
ENTRY(Reset_Handler)

_estack = ORIGIN(RAM) + LENGTH(RAM);

_Min_Heap_Size  = 0x400;
_Min_Stack_Size = 0x800;

ENTRY tells the linker (and a debugger reading the ELF) the program's first function. It does not affect where the core starts: that comes from the vector table. _estack is a symbol whose value is the address one past the last byte of RAM, and the vector table's first word uses it. The two _Min_ symbols are not variables either. They are constants the script uses later to reserve space.

Step 3: the vector table and code

The first output section in flash must be the vector table, then code and read-only data:

Text
SECTIONS
{
  .isr_vector :
  {
    . = ALIGN(4);
    KEEP(*(.isr_vector))
    . = ALIGN(4);
  } > FLASH

  .text :
  {
    . = ALIGN(4);
    *(.text)
    *(.text*)
    *(.rodata)
    *(.rodata*)
    KEEP(*(.init))
    KEEP(*(.fini))
    . = ALIGN(4);
    _etext = .;
  } > FLASH

The location counter . is the current address inside the output section. ALIGN(4) rounds it up to a multiple of four, which keeps word-sized copies in the startup code valid. *(.text*) matches .text, .text.main, and the per-function sections that -ffunction-sections generates, from every input file. KEEP on .isr_vector tells --gc-sections that the table is used even though no code refers to it.

Because .isr_vector comes first and goes to FLASH, it starts at 0x08000000. Section order in the script is the order in the image.

Step 4: the C++ and init arrays

If any code uses constructors or __attribute__((constructor)), the toolchain needs these arrays (they are harmless if empty):

Text
  .preinit_array :
  {
    PROVIDE_HIDDEN(__preinit_array_start = .);
    KEEP(*(.preinit_array*))
    PROVIDE_HIDDEN(__preinit_array_end = .);
  } > FLASH

  .init_array :
  {
    PROVIDE_HIDDEN(__init_array_start = .);
    KEEP(*(SORT(.init_array.*)))
    KEEP(*(.init_array*))
    PROVIDE_HIDDEN(__init_array_end = .);
  } > FLASH

  .fini_array :
  {
    PROVIDE_HIDDEN(__fini_array_start = .);
    KEEP(*(SORT(.fini_array.*)))
    KEEP(*(.fini_array*))
    PROVIDE_HIDDEN(__fini_array_end = .);
  } > FLASH

PROVIDE_HIDDEN defines the symbol only if no object file defines it, and hides it from the dynamic symbol table. newlib's __libc_init_array walks from __init_array_start to __init_array_end, calling each function pointer. SORT orders entries by priority suffix, which is how constructor(101) runs before constructor(200).

Step 5: initialised data, the two addresses

.data is the section that needs both a flash address and a RAM address:

Text
  _sidata = LOADADDR(.data);

  .data :
  {
    . = ALIGN(4);
    _sdata = .;
    *(.data)
    *(.data*)
    . = ALIGN(4);
    _edata = .;
  } > RAM AT > FLASH

Read > RAM AT > FLASH as: the section's virtual (run) address is in RAM; its load address is in FLASH. The linker places the bytes in the flash image after .text, then relocates every reference to a .data variable to its RAM address. LOADADDR(.data) returns the flash address, so _sidata is the copy source, _sdata and _edata bound the destination.

You can see both addresses in the section headers (the VMA and LMA columns):

Text
arm-none-eabi-objdump -h firmware.elf
Text
Idx Name          Size      VMA       LMA       File off  Algn
  0 .isr_vector   00000188  08000000  08000000  00010000  2**2
  1 .text         00001a30  08000188  08000188  00010188  2**2
  2 .data         00000014  20000000  08001bb8  00020000  2**2
  3 .bss          0000004c  20000014  20000014  00020014  2**2

.data has a VMA in RAM (20000000) and an LMA in flash (08001bb8, right after .text). The sizes here are an example from a small build and will differ. .bss has the same VMA and LMA because it takes no space in flash.

Step 6: zeroed data

Text
  .bss (NOLOAD) :
  {
    . = ALIGN(4);
    _sbss = .;
    *(.bss)
    *(.bss*)
    *(COMMON)
    . = ALIGN(4);
    _ebss = .;
  } > RAM

.bss is zero-initialised data. The NOLOAD type marks it as not part of the loaded image, though for .bss, which has the NOBITS type already, it is mostly documentation. COMMON collects uninitialised globals from old-style C that were not given a definite section; modern GCC defaults to -fno-common since version 10, but the line is harmless.

Step 7: heap and stack with a guard

A well-formed script reserves heap and stack space and checks it:

Text
  ._user_heap_stack :
  {
    . = ALIGN(8);
    PROVIDE(end = .);
    PROVIDE(_end = .);
    . = . + _Min_Heap_Size;
    . = . + _Min_Stack_Size;
    . = ALIGN(8);
  } > RAM

This section has no contents. It moves the location counter forward by the minimum heap and stack sizes. If the static data and the reservations do not fit in RAM, the link fails with an overflow error instead of a runtime crash. The symbols end and _end mark where the heap starts, which newlib's _sbrk implementation reads. The stack grows down from _estack, so the reserved space is its worst case floor as far as the link is concerned: the linker cannot tell whether your stack really stays within it.

Step 8: discard what you do not want

Text
  /DISCARD/ :
  {
    libc.a ( * )
    libm.a ( * )
    libgcc.a ( * )
  }

  .ARM.attributes 0 : { *(.ARM.attributes) }
}

/DISCARD/ drops input sections from the output. The linker gives each input section to the first script statement that matches it, so .text and .data have already claimed everything useful by the time the /DISCARD/ block is reached. What lands there is the leftover: sections from the three libraries that no earlier pattern matched, such as unwind tables, which a bare-metal image does not need. The GNU ld manual describes this first-match rule in its section on input section placement. .ARM.attributes 0 places the section at address zero, outside any region, so it stays in the ELF for tools but not in the image.

Checking the script

Two linker options turn the script into something verifiable:

Text
arm-none-eabi-gcc ... -Wl,-T,link.ld -Wl,-Map=firmware.map -Wl,--print-memory-usage
Text
Memory region         Used Size  Region Size  %age Used
           FLASH:        7096 B         1 MB      0.68%
             RAM:        3948 B       128 KB      3.01%

--print-memory-usage prints the table after the link. The numbers above are an example for a small program, in which the RAM figure includes the reserved heap and stack. The map file lists every section with its address and the object file it came from.

Add an assertion for things you can check at link time:

Text
ASSERT(_estack == 0x20020000, "RAM end moved: check the MEMORY block")
ASSERT(. <= ORIGIN(FLASH) + LENGTH(FLASH), "image too large for flash")

ASSERT fails the link with your message. It is the right tool for invariants, such as the vector table being first, that a code review would otherwise have to catch.

What this script does not do

It ignores the CCM region, external memory and bootloader offsets. It makes no distinction between .rodata that should live in flash and read-only data you might want in RAM. A project with a boot loader adds an ORIGIN offset to FLASH. A project with DMA buffers adds a section in SRAM that is not cached on parts with data caches. Each is a few more lines in the same pattern.

Also inToolchains
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.