Topics / Embedded C / Q14
What is a linker script and what does it contain?
Short answer: A linker script tells the linker what memory the target has and where each output section (code, constants, initialised data, zeroed data, stack, heap) goes. It defines MEMORY regions (start address, size, permissions) and a SECTIONS command mapping input sections to output sections and regions, and it exports symbols (such as _sdata, _ebss, _estack) that the start-up code uses.
MEMORY
{
FLASH (rx) : ORIGIN = 0x08000000, LENGTH = 512K
RAM (rwx) : ORIGIN = 0x20000000, LENGTH = 128K
}
_estack = ORIGIN(RAM) + LENGTH(RAM); /* initial stack pointer: top of RAM */
SECTIONS
{
.isr_vector : { KEEP(*(.isr_vector)) } > FLASH /* KEEP: never garbage-collect */
.text : { *(.text*) *(.rodata*) . = ALIGN(4); } > FLASH
_sidata = LOADADDR(.data);
.data : { _sdata = .; *(.data*) . = ALIGN(4); _edata = .; } > RAM AT> FLASH
.bss (NOLOAD) : { _sbss = .; *(.bss*) *(COMMON) . = ALIGN(4); _ebss = .; } > RAM
.noinit (NOLOAD) : { *(.noinit*) } > RAM /* not zeroed at start-up */
._user_heap_stack : { . = ALIGN(8); . += 0x1000; . += 0x800; } > RAM /* reserve heap + stack, fail link if no room */
}
Key concepts
- VMA vs LMA:
.datahas a run address (VMA) in RAM and a load address (LMA) in flash (> RAM AT> FLASH). The start-up code copies from LMA to VMA. KEEPstops--gc-sectionsfrom removing sections nothing references explicitly (vector table, init arrays).NOLOADsections take no space in the output image.- Symbols defined in the script have an address but no storage; in C you use
&_sdata. - The linker fails with "region `RAM' overflowed" if things do not fit, which is better than finding out at run time.
Common reasons to edit a linker script
- Leave room for a bootloader (application starts at
0x08008000), or for configuration/calibration data in a reserved flash sector. - Place time-critical code in RAM or ITCM, and DMA buffers in a specific (non-cacheable or DMA-reachable) RAM bank.
- Add a
.noinitarea for crash logs or a bootloader-to-application mailbox. - Use external memory (QSPI flash for graphics, SDRAM for frame buffers).
- Insert a firmware header (version, CRC, size) at a fixed offset.
Check the result in the map file (-Wl,-Map=fw.map) and with arm-none-eabi-size -A fw.elf.