Monday, March 7, 2011

Packing structures \ enums

There are various ways in which this can be done.

1. using #pragma pack()

#pragma pack(2)
typedef struct
{
char c;
int i;
} DataType;
#pragma pack()


This would pack the structure on a 2 byte boundary. If a tight packing is required use #pragma pack(1) instead. Compile it normally using gcc.

2. Using -fpack-struct
Instead of using the #pragma, we can directly use the compiler flags instead.

$gcc -Wall -fpack-struct -fshort-enums test.c -o test

This would pack all the structs to the 1 byte boundary and consider shorts for enums instead of integers

2. Using __attribute__ ((__packed__))


typedef struct
{
char c;
int i;
} __attribute__ ((__packed__))DataType;

.
Compile the code normally.

We can also do it this way


typedef struct
{
char c __attribute__ ((__packed__));
int i1 __attribute__ ((__packed__));
int i2;
} DataType;

No comments:

Post a Comment