How promising is the forced alignment of the structure with `__attribute __ ((packed, aligned (N)))?

I have a structure whose relevant part is:

typedef struct { uint64_t *num; ... } name; 

Naturally, in most architectural elements there is an alignment of 8, but for reasons (obsolete reasons) I need it to have an alignment of 4, since I can guarantee the last alignment, but not the first.

The solution I found adds __attribute__((packed,aligned(4))) to the declaration.
I tested it on godbolt.com and it really works and produces the right amount of workload for each architecture that they have.

GCC docs do not mention this combination, and clang docs do not mention these attributes at all.

My question is: how portable (between unix-like environments) and the future? Can the next year GCC / clang break it all?

Should I use #pragma pack(4) for it, which looks almost equivalent?

+5
source share
2 answers

__attribute__(packed) for gcc, some other compilers like clang can understand this, but others like visual studio won't ... The C compiler will use whatever is normal for abi, see: The Lost Art of C structure packing

truly the best you can do is find the optimal natural packaging:

order them from the largest to the smallest ... and you will get the smallest structure, naturally packaged ...

or if you need to use GCC only for Linux, then just use the packed attribute and continue to talk about your fun route, know that it will not work everywhere.

+2
source

Yes, all of this could be broken in any future version. Compilers only need to implement the C standard and reserve the right to revoke the subtleties that you rely on, especially if their implementation becomes impossible in future architectures.

This may be quite simplistic, but it’s best to hit old issues. For me, this is part of the "always fix bugs before writing new code" genre.

+1
source

Source: https://habr.com/ru/post/1272279/


All Articles