Using uVision 5.12.0.0 (ARM) I need my variables to be placed in the order I declare them. But when I look at the map-file they are not. The types I use are unsigned) char, (unsigned) int, and arrays of these types.
Question 1: How are variables placed in memory? Question 2: How can I control the order, there is no #pragma ORDER (as was in C166)? Question 3: Any alternatives, besides placing them in a structure?
Thanks.
Sorry, I'm not sure how they are ordered, but have you checked if the compiler rearranges them to maintain alignment without excess padding? And are you sure the compiler did rearrange the order and did not just add padding?
Having an int, a char and an int after each other would require three bytes of padding to get the second int properly aligned.
Then put them in a struct ?
Yes, this isn't just passing, I'm using the pack-pragma to prevent this. And when padding is added to maintain alignment this only inserts bytes between variables, it doesn't rearrange them.
Yes, in a struct. That way the order is maintained, and when using the pack-pragma this creates a memory-layout you have control over.
But packed structs are quite often very painful.
If mapping on top of hardware, then the hardware registers are normally properly aligned to avoid the need for strange packed constructs.
When handling protocols, it's often better to use own source code working with a void* or uint8_t* pointer for building/decoding packets, since that also takes care of byte order.
Another issue when having packed structs mapped to hardware is the implication of volatile underlying registers assumed to be accessed using a single read or a single write. Or assuming that maybe low word must be accessed before high word - or reversed - to latch and read out a wide value.