Variable Placement in memory

Thread Starter

gogo00

Joined Oct 28, 2023
37
Hey there,

I'm exploring how compilers decide where to place variables in a microcontroller's memory. Does this allocation rely on the microcontroller's memory architecture or the compiler manufacturer's choices? I've come across the division of memory into four categories in a c language:

Text: Reserved for program instructions.
Data: Used for storing global variables.
Stack: Reserved for local variables.
Heap: For dynamic memory allocation.
Would you happen to have any insights into this?

Thanks!
 

ApacheKid

Joined Jan 12, 2015
1,609
Hey there,

I'm exploring how compilers decide where to place variables in a microcontroller's memory. Does this allocation rely on the microcontroller's memory architecture or the compiler manufacturer's choices? I've come across the division of memory into four categories in a c language:

Text: Reserved for program instructions.
Data: Used for storing global variables.
Stack: Reserved for local variables.
Heap: For dynamic memory allocation.
Would you happen to have any insights into this?

Thanks!
It needs to be stressed that what a compiler does is not quite what most books say. In reality a compiler produces a file, a file that has a definite structure. The file is then an input to a linker and that produces another file the executable or loadable memory image.

If you look at how these files are structured you'll get some insights into how decisions are made about memory layout.

The compiler is usually built around the concepts of stack, static and heap. Variables that are stack based are described in the compiler's output file, as offsets from a stack frame's base address, static variables are described as an offset from a static base address.

Often/Usually there is one contiguous region for static variables and every static variable is at some offset from the start address.

Stack frames are "chunks" of memory created on the stack as code invokes other code. Every call from one function into another causes a chunk to be allocated from the stack for that stack frame, all stack variables are at an offset from the start of that stack frame.

Most real code is multiple source files, each compiled into their own output file and those outputs are then analyzed to create the final executable file.

Read about the file structures, this will give you insights, compilers do all this work to define these regions, size them and so on, they do much more that "convert source into machine code", that's a glib and highly simplified description of what a compiler does.

e.g. Texas Instruments.
 
Top