Electronics > Beginners
Effect of variable size in microcontrollers.
DG41WV:
Hi, I would like to know if there is any advantage in using variables that are smaller than the ram size. for example the STM32F103C8 seems to have a 32bit wide ram. would a 8bit variable take up the whole address or can the compiler put more variables in that memory. I'm using the GCC compiler btw.
T3sl4co1l:
The compiler will do whatever you tell it to.
What do you really want to do? Optimize for code size? RAM use? Speed?
Tim
exit_failure:
This is not something that can be answered universally as it depends on the interplay of the processors architecture and the exact compilation options you choose.
For example there is alignment and padding. This becomes especially important if you use data types of different lengths. These describe how your data is stored in RAM. There always will be a trade-off between memory usage and access time. Usually this it not something that is determined on a hardware level but by compiler options
The Wikipedia article explains it quite well:
https://en.wikipedia.org/wiki/Data_structure_alignment
Please feel free to ask, if you don't understand something or have any other questions left.
stmdude:
In _this particular case_, GCC would behave like this:
--- Code: ---uint8_t a,b;
printf(%p,%p\n",&a,&b);
0x10000000,0x10000004
--- End code ---
Because it's more efficient (faster) for it to fetch on a 4-byte boundary.
However, you can tell GCC that you care more about size than speed like this:
--- Code: ---#pragma pack(1) // Set packing/alignment to 1 byte
uint8_t a,b;
#pragma pack() // Restore default packing
printf(%p,%p\n",&a,&b);
0x10000000,0x10000001
--- End code ---
(All this is typed from memory, so.. No guarantees, but this is basically how it works)
DG41WV:
Thanks for the answers.
I'm not particularly trying to do something specific, but was just curious of what would happen if I used a uint16_t instead of a uint8_t. So, from the answers on this thread it would be safe to assume unless you ask the compiler to optimize for space, it would use a whole address space on the ram, right?
Navigation
[0] Message Index
[#] Next page
Go to full version