#pragma pack(1) vs __attribute__((packed))

Braden Obrzut admin@maniacsvault.net
Sun Jun 7 09:28:00 GMT 2015


I compiled GCC 5.1 on my PowerMac today and noticed that zip archive 
reading broke in my program.  Upon investigation it seems like GCC is 
adding padding (presumably trailing) to a structure which represents a 
chunk of the archive on disk, which has been declared within #pragma 
pack(1).  Adding __attribute__((packed)) to the structure does bring the 
structure to the correct size, but from what I understand this is a GCC 
specific feature.

The following structure can demonstrate the problem on PowerPC:

struct S1 {
     uint32_t x;
     uint16_t y;
};

On x86 #pragma pack(1) will make sizeof(S1) == 6.  On PowerPC without 
__attribute__((packed)) it is 8.  I do believe I found #pragma pack to 
be working as some other, more complex, structures end up with less 
padding, but not to the extent of the attribute. (Somewhat peculiarly, 
swapping the two members results in the structure being the expected 
size.  I assume it's done to try to keep accesses to x aligned, and in 
the swapped case not padding the end means the access would be aligned 
every other array element.)

Is this difference in behavior between the two features, which sound 
like they should be doing the same thing, intentional?  The change 
appears to have happened around GCC 4.4 as 4.2 behaves as expected 
(haven't tested 4.3 yet).

- Braden Obrzut



More information about the Gcc mailing list