Weird structure size


#1

Hi all,
Check this out. I’m using the GCC compiler and I’m getting an erroneous structure size for the following structure:

typedef struct {
u8 SynCh1;
u8 SynCh2;
u16 IDClass;
u16 PayloadLength;
} UBXHeaderStruct;

I’m printing the structure size on the serial port, along with the members size and I get this:

sprintf( szTemp, “U8 = %u U16 = %u STRUCT = %u”, sizeof(u8), sizeof (u16), sizeof (UBXHeaderStruct));

U8 = 1 U16 = 2 STRUCT = 8

STRUCT should be 6!!! UBXHeaderStruct is used as a part of a larger structure:

typedef struct {
UBXHeaderStruct Header;
u16 flags;
u16 pins;
} UBXCFGANTStruct;

I discovered the problem when I was trying to access the flags member from the latter structure. I was always getting a wrong value, obviously because of the wrong size of UBXHeaderStruct.

Does anyone know what could be wrong? Any suggestions are welcome.


#2

Hello,

Nothing wrong, it’s called padding. If you want to change the alignment settings use the “attribute(())” directive in GCC.

Here is my solution to define a structure packed (aligned to 1 byte boundary) in Visual C and in GCC compiler at the same time. Maybe it is not the nicest method, but i didn’t find a better solution so if somebody has a more elegant way don’t hide it.

xpragmagcc.h

#ifdef __GNUC__
__attribute__((packed))
#else
//nothing
#endif

xpragma_start.h

#ifdef __GNUC__
//nothing
#else
#pragma pack(push,1)
#endif

xpragma_end.h

#ifdef __GNUC__
//nothing
#else
#pragma pack(pop)
#endif

Here is the packed structure, which size is 6:

#include "xpragma_start.h"
typedef struct
{
	u8 element_1;
	u8 element_2;
        u32 element_3;
}
#include "xpragmagcc.h" 
THIS_IS_A_PACKED_STRUCT;
#include "xpragma_end.h"

Cheers,
tom


#3

Thank you Tom, that helped me a lot.

Oratios