Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare packed struct (without padding) for LLVM?

Tags:

People also ask

How do you prevent struct padding?

In Structure, sometimes the size of the structure is more than the size of all structures members because of structure padding. Note: But what actual size of all structure member is 13 Bytes. So here total 3 bytes are wasted. So, to avoid structure padding we can use pragma pack as well as an attribute.

Why does structure padding happen?

The structure padding is automatically done by the compiler to make sure all its members are byte aligned. Here 'char' is only 1 byte but after 3 byte padding, the number starts at 4 byte boundary. For 'int' and 'double', it takes up 4 and 8 bytes respectively.

What is Pragma pack1?

When you use #pragma pack(1) , this changes the default structure packing to byte packing, removing all padding bytes normally inserted to preserve alignment.

Why does the compiler sometimes insert padding between fields and or at the end of a struct?

Compilers are free to insert padding between fields, and following the final field (but not before the first field). This is usually done for performance as some types perform better when they're aligned on specific boundaries.


It's possible to tell GCC it should not use padding for the struct. This is done using __attribute__((packed)).

typedef struct {

  uint8_t startSymbol;
  uint8_t packetType;
  uint32_t deviceId;
  uint16_t packetCRC;

} PacketData __attribute__((packed));

However, newest Xcode uses LLVM and does not recognize the attribute. How to define packed struct for LLVM?

The full description of the problem might be found here

UPDATE I'm using Xcode 4.5.1 for iOS which uses Apple LLVM 4.1 compiler. I'm getting "'packed' attribute ignored" warning in Xcode in the code example above.