Packed Structures

cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 

Packed Structures

3,762 Views
lpcware-support
Senior Contributor I

By default, GCC does not pack structures so it will in general leave spaces so that data items are word aligned. This behavior can be changed by using the "packed" attribute on the structure.

struct foo
{  short a;
   char b;
   int c;
   char d;
} __attribute__((packed));

Some other toolchains have alternative ways of packing structures. For example a particular toolchain might use a qualifier "__packed" which needs to be placed before the structure rather than using an attribute after the structure. The following code snippet shows how code might be written to allow the code to be compilable using either toolchain...

#if defined(__GNUC__)   // LPCXpresso Tools
  #define PRE_PACK
  #define POST_PACK     __attribute__((packed))
#else                   // Other toolchain
  #define PRE_PACK      __packed
  #define POST_PACK
#endif

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

PRE_PACK struct foo
{  short a;
   char b;
   int c;
   char d;
} POST_PACK ;

Note: packing data can have code size and performance overheads so is not recommended for general use. However there are some circumstances where you may need to make use of it - for example for accessing data coming in from peripherals.

#pragma pack

For compatibility with certain other toolchains GCC also offers a pragma which can be used to control the packing of structures.

For more details see the GCC documentation: Structure-Packing Pragmas

Labels (1)
Tags (2)
0 Kudos
Reply
0 Replies