Topic : Data alignment in structures

Forum : ST7/STM8

Original Post
Post Information Post
June 3, 2010 - 1:40pm
Guest

Hi,
I am using 8-bit ST processor and STM8 Compiler version 2.28.10.
Does data order in structures make any difference in code size? Because some compilers recommend structures like s_Example2 to make alignment better. The examples are below.

struct s_Example1{
char c_variable1;
int i_variable2;
long l_variable3;
char c_variable4;
};

struct s_Example2{
char c_variable1;
char c_variable4;
int i_variable2;
long l_variable3;
};

Replies
Post Information Post
+1
0
-1
June 3, 2010 - 2:21pm
Raisonance Support Team

Hi Volkan,

RCSTM8 uses byte-alignment for structure members, so you do not have to mind about this. This is because the STM8 data bus does not suffer from misaligned data, so there is no need to align RAM data (Flash data should be 16-bit aligned on STM8 for fastest access)

Note however that it is a good rule to follow as simple as this: Align structure members on a multiple of their own size. This means that "char" variables can go wherever you like (8-bit aligned), 'short' should be aligned on 16-bit and long/float should be 32-bit aligned. This will make your structures portable and fast on most architectures.

So your second example is better if code portability is a concern.

Another side rule is to place largest structure members first (except for arrays), so your third (best) solution would probably be:

struct s_Example3 {
   long l_variable3;
   int i_variable2;
   char c_variable1;
   char c_variable4;
};

Also 2 notes (just for fun):
- 'int' is not portable, you may prefer using 'short'.
- 'char' is not portable, you should explicitly have 'signed char' or 'unsigned char'.

Enjoy,
Bruno

+1
0
-1
June 4, 2010 - 1:55pm
Guest

Thank you for your advice Bruno!

I will pay attention to your notes.