I have a struct, whose relevant part is:
typedef struct {
uint64_t *num;
...
} name;
It would naturally have alignment 8 in most architectures, but for reasons (legacy reasons), I need it to have alignment 4, as I can guarantee the latter alignment, but not the former.
A solution I've found is adding __attribute__((packed,aligned(4)))
to the declaration.
I've tested it at godbolt.com and it indeed works and produces the correct number of loads on every architecture they have.
GCC docs make no special mention for this combination and clang docs don't mention these attributes at all.
My question is, how portable (between unix-like environments) and future-proof would this be?
Could next year's GCC/clang break the whole thing?
Should I prefer #pragma pack(4)
to it, which looks pretty much equivalent?
__attribute__(packed)
is for gcc, some other compilers like clang may understand it but others like visual studio wont... The C compiler will use whatever is normal for the abi, see: The Lost Art of C Structure Packing
really the best thing you can do is find an optimal natural packing:
order them from largest to smallest... and you will end up with the smallest struct naturally packed...
or if you only need to use GCC on linux then just use the packed attribute and go on about your merry way, know that it wont work everywhere.
Yes the whole thing could be broken in any future release. Compilers only need to implement the C standard, and reserve the right to withdraw such niceties as you are relying upon, particularly if their implementation becomes unfeasible in future architectures.
It might be rather simplistic, but your best bet is to hit the legacy issues head on. To me this comes into the "always fix bugs before writing new code" genre.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With