Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How future-proof is it to force a structure alignment with `__attribute__((packed,aligned(N)))`?

Tags:

c

gcc

clang

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?

like image 459
12345ieee Avatar asked Oct 18 '22 05:10

12345ieee


2 Answers

__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.

like image 71
Grady Player Avatar answered Nov 15 '22 05:11

Grady Player


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.

like image 21
Bathsheba Avatar answered Nov 15 '22 05:11

Bathsheba