Course contentsShow
← Embedded Systems & Computer Architecture
Lesson 439 of 9366. Embedded Software Construction and ToolchainsFree lesson

Defining Memory Regions with MEMORY Commands

You will define the physical address ranges of your hardware's RAM and Flash memory within a linker script.

In this lesson, you will learn how to explicitly map your hardware’s physical memory layout into your linker script using the MEMORY command.

Mapping the Physical Reality

As you know from our work with ELF files and section management, the linker needs to know where it is allowed to place code and data. While the compiler generates objects based on source code, the linker script acts as the master blueprint. If you don't define the memory regions, the linker has no way to distinguish between non-volatile Flash and volatile RAM.

The MEMORY command provides this mapping by defining the names, starting addresses, and total sizes of your hardware’s memory blocks.

Syntax and Implementation

The MEMORY command is placed at the top level of your linker script. Inside the braces, you define each region, specifying its attributes (like Read, Write, or Execute permissions) and its physical address boundaries.

Consider this example for a typical microcontroller:

MEMORY
{
    /* Flash starts at 0x08000000 and is 512KB */
    FLASH (rx) : ORIGIN = 0x08000000, LENGTH = 512K
    
    /* RAM starts at 0x20000000 and is 128KB */
    RAM (rwx)  : ORIGIN = 0x20000000, LENGTH = 128K
}

In this block:

  • FLASH (rx): We assign the name FLASH, tagging it as read-only and executable. This is where your instructions (.text sections) will reside.
  • RAM (rwx): We assign the name RAM, tagging it as read, write, and executable. This is where your variables (.data and .bss sections) will reside.
  • ORIGIN: The base address of the memory bank as defined in your hardware datasheet.
  • LENGTH: The physical capacity of that specific memory block.

Why It Matters

By explicitly defining these regions, you enable the linker to catch critical errors. If your code or data exceeds the LENGTH defined, the linker will throw a "region overflow" error during the linking process. This prevents you from inadvertently writing beyond your physical hardware limits, which would otherwise result in silent failures or hard faults during execution.

Key Takeaway: The MEMORY command is your primary mechanism for enforcing physical hardware constraints, ensuring that the linker knows exactly where your code and data are permitted to live within the address space.