Wednesday, January 5, 2011

GCC byte alignment for data structure

[1] http://www.velocityreviews.com/forums/t651650-does-gcc-has-compile-option-for-bytes-alignment.html
[2] detailed gcc user manual see http://gcc.gnu.org/onlinedocs/gcc-4.3.5/gcc.pdf

IN GCC
---------------------------------------------
__attribute__((aligned(4)))
__attribute__((packed))


#include
#include

struct struct_1{
unsigned char byte1;
unsigned short word2;
unsigned char byte3;
unsigned char byte4;
unsigned char byte5;
}__attribute__((aligned(1)));

struct struct_1_packed{
unsigned char byte1;
unsigned short word2;
unsigned char byte3;
unsigned char byte4;
unsigned char byte5;
}__attribute__((packed));

struct struct_2{
unsigned char byte1;
unsigned char byte2;
unsigned char byte3;
unsigned char byte4;
unsigned char byte5;
}__attribute__((aligned(1)));


int main (int argc, char *argv[])
{
struct struct_1 One;
struct struct_2 Two;
struct struct_1_packed Three;

printf("size of struct one is %d\n",sizeof(struct_1));
printf("size of struct two is %d\n",sizeof(struct_2));
printf("size of struct three is %d\n",sizeof(struct_1_packed));


}

ScreenPrint 'size of struct one is 8'
'size of struct two is 5'
'size of struct two is 6'




IN PIC32
------------------------------------------
typedef struct cableTrackerConfigFrHostStruct
{
S_CABLETRACKER_CONFIG_COM sComConfig;
S_CABLETRACKER_CONFIG_DAQ sDaqConfig;
GSNTYPES_USHORT iChkSum;
}
#ifdef TARGET
__attribute__((packed)) S_CABLETRACKER_CONFIG_IN_SDCARD;
#else
S_CABLETRACKER_CONFIG_IN_SDCARD;
#endif

No comments: