Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pragma pack(1) nor __attribute__ ((aligned (1))) works

My code used to work in the past, but now the struct size suddenly is 16 bytes. It used to be 13 bytes. I recently upgraded from Xcode 4.2 to Xcode 4.3.1 (4E1019).

#pragma pack(1)
struct ChunkStruct {
    uint32_t width;
    uint32_t height;
    uint8_t bit_depth;
    uint8_t color_type;
    uint8_t compression;
    uint8_t filter;
    uint8_t interlace;
};
#pragma pack()
STATIC_ASSERT(expected_13bytes, sizeof(struct ChunkStruct) == 13);

I have tried unsuccesfully using

#pragma pack(push, 1)
/* struct ChunkStruct { ... }; */
#pragma pack(pop)

I have also tried the following, but no luck

struct ChunkStruct {
    uint32_t width;
    uint32_t height;
    uint8_t bit_depth;
    uint8_t color_type;
    uint8_t compression;
    uint8_t filter;
    uint8_t interlace;
} __attribute__ ((aligned (1)));

How to pack structs with Xcode 4.3.1 ?

like image 215
neoneye Avatar asked Apr 29 '12 10:04

neoneye


People also ask

What does __ Attribute__ packed )) Meaning?

__attribute__((packed)) variable attributeThe attribute specifies that a member field has the smallest possible alignment. That is, one byte for a variable field, and one bit for a bitfield, unless you specify a larger value with the aligned attribute.

How does pragma Pack work?

The #pragma pack directive modifies the current alignment rule for only the members of structures whose declarations follow the directive. It does not affect the alignment of the structure directly, but by affecting the alignment of the members of the structure, it may affect the alignment of the overall structure.

What does #pragma pack 1 mean?

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

What does attribute aligned do?

The aligned attribute only increases the alignment for a struct or struct member. For a variable that is not in a structure, the minimum alignment is the natural alignment of the variable type. To set the alignment in a structure to any value greater than 0, use the packed variable attribute.


1 Answers

Xcode uses the gcc and clang compilers which both use __attribute__((packed)) to designate struct packing.

struct foo {
  uint8_t bar;
  uint8_t baz;
} __attribute__((packed));

Using __attribute__((aligned(1))) tells the compiler to begin each struct element on the next byte boundary but doesn't tell it how much space it can put at the end. This means that the compiler is allowed to round the struct up to a multiple of the machine word size for better use in arrays and similar. __attribute__((packed)) tells the compiler to not use any padding at all, even at the end of the struct.

like image 169
Will Avatar answered Oct 03 '22 19:10

Will