Weird structure size


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;

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.



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.


#ifdef __GNUC__


#ifdef __GNUC__
#pragma pack(push,1)


#ifdef __GNUC__
#pragma pack(pop)

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" 
#include "xpragma_end.h"



Thank you Tom, that helped me a lot.