Linker Memory File

The GCC linker is a complex program, allowing a lot of flexibility in how memory segments are laid out and assigned to C/C++ address areas. A linker memory file contains commands to tell the linker how to allocate the target memory. The linker memory file is usually named flash.ld and is specified via the -T option in the Project->Build Options->Compiler/Linker tab, as described above.


For advanced users, you may edit this file by hand. CodeBlocks generates an automatic dependency, so that if the file is modified, it will cause the project to relink when you invoke the build command.


GCC linker memory files can be very complex, and it is beyond the scope of this document to describe their format and semantics in detail. A web search should provide more in-depth information if you are interested.

Specifying the Heap and Stack Sizes

It is beyond the scope of this document to describe the linker memory commands. However, take note of these two lines in the file:


_Min_Heap_Size   = 0x2aa;   /* required amount of heap  */

_Min_Stack_Size  = 0x800;   /* required amount of stack  */


They specify the heap and stack size for the program. Heap is the SRAM memory region which the C library memory allocation functions (e.g. malloc and free) use to allocate the dynamic memory blocks, and the stack is the space used for allocating local variables and other data which are required for function implementations. All data: global variables, stack, heap, etc., must share the same SRAM space.


Heap and stack are allocated in the same memory block with the heap starting at the low address and the stack starting at the high address. The heap “grows” upward toward the stack and the stack “grows” downward toward the heap. See Output File Memory Usage.


NOTE: if you use one of the IDE’s wizards to generate a project, the associated linker memory files have different stack and heap settings based on the target device memory size. You should adjust the values to suit your needs. Also, if you switch the target to a different device with different SRAM, you should also adjust these settings.

Memory Problems

As most Cortex-M MCUs do not have memory protection and their amount of SRAM is limited, a program will fail if the stack or heap grows too large and they “bump” into each other or other memory addresses already being used (e.g. global variables). If that happens, you need to either change your program or adjust these values. NOTE: there is usually no indication when the stack and heap accidentally “grow” into each other, other than the program crashing, which may not always occur at the same spot. This type of error and other “memory overwrite” problems can be difficult to track down.