Packed Structures

取消
显示结果 
显示  仅  | 搜索替代 
您的意思是: 

Packed Structures

3,196 次查看
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

标签 (1)
标记 (2)
0 项奖励
0 回复数