Defining Physical Memory Regions with MEMORY Commands
In this lesson, you will learn how to use the linker script's MEMORY command to translate raw hardware addresses into logical regions that your code can safely utilize.
The Problem of Raw Addresses
In bare-metal programming, your microcontroller’s hardware manual provides a massive map of memory. For example, your Flash memory might start at 0x08000000, while your SRAM starts at 0x20000000. If you simply let the linker place code and data wherever it wants, it might accidentally put a variable in the middle of your program code or overflow into restricted peripheral space.
Using the MEMORY Command
The MEMORY command acts as a "map" that tells the linker exactly where physical memory exists and what kind of permissions each region has. This prevents the linker from placing data in invalid locations and allows it to throw an error if your code exceeds the available space.
Here is a typical structure you might define in your linker script:
MEMORY
{
FLASH (rx) : ORIGIN = 0x08000000, LENGTH = 512K
RAM (rwx): ORIGIN = 0x20000000, LENGTH = 128K
}
Breaking Down the Syntax
- Name:
FLASHandRAMare labels we define for our convenience. - Attributes: The characters in parentheses define access permissions:
r: Readablew: Writablex: ExecutableFLASHis marked(rx)because code is read and executed, but not typically modified at runtime.RAMis marked(rwx)because we need to read, write, and occasionally execute code (or store data) there.
- ORIGIN: The starting physical address of the hardware block.
- LENGTH: The total capacity of that memory block.
By defining these regions, you create a formal contract between your software and the physical silicon. If you attempt to assign too much code to FLASH, the linker will immediately alert you during the build process, preventing a runtime system failure that would be much harder to debug.
Key Takeaway: The MEMORY command transforms abstract hardware addresses into structured, permission-gated regions, allowing the linker to enforce memory safety and capacity limits before your code even reaches the processor.