cnetwork-programminggccstruct

Does GCC's __attribute__((__packed__)) retain the original ordering?


Purpose

I am writing a network program in C (specifically gnu89) and I would like to simplify things by reinterpreting a certain struct X as big array of bytes (a.k.a. char), sending the bytes over the network, and reinterpreting them as struct X on the other side. To this end I have decided to use gcc's __attribute__((__packed__ )). I have done my best to ensure that this is done correctly (i.e. I've accounted for endianness and other related issues).

Question

Other than guaranteeing that struct X is as small as possible, does gcc guarantee that a struct defined with __attribute__((__packed__ )) retains the original ordering? I've done a fair amount of searching and I have yet to find any documentation on whether or not this guarantee exists.

Notes

It is safe to assume that both the sender and receiver will encounter no portability issues (e.g. sizeof(int) on the server is equal to sizeof(int) on the client).


Solution

  • Assuming that you are asking whether the struct members will retain the order specified in their definition, the answer is yes. The Standard requires that successive members have increasing addresses:

    Section §6.7.2.1p13:

    Within a structure object, the non-bit-field members and the units in which bit-fields reside have addresses that increase in the order in which they are declared.

    and the documentation for the packed attribute clearly states that only padding/alignment is affected:

    The packed attribute specifies that a variable or structure field should have the smallest possible alignment—one byte for a variable, and one bit for a field, unless you specify a larger value with the aligned attribute.