NOTICE: This website will be shut down in the near future. Product content has moved to Forum content and FAQs have been moved to We encourage you to create a user account on to use the new community forums and access NXP microcontroller content. We greatly appreciate your contributions and look forward to seeing you at our new web location.


Packed Structures

lpcxpresso-support's picture

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
PRE_PACK struct foo
{  short a;
   char b;
   int c;
   char d;

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 compatability 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.

Your rating: None