I have a question which is best explained by example. Please consider the following code:
unsigned char a,
b;
This obviously defines two variables of type unsigned char
.
If I would like to make the variables aligned to 16-byte-boundaries, my first naive approach would be this:
__attribute__((aligned(16))) unsigned char a,
b;
My problem is that I am not sure whether the compiler always applies __attribute__((aligned(16)))
to both variables.
I am particularly worried because all of the following code is compiled without errors or warnings:
unsigned char a __attribute__((aligned(16)));
unsigned char __attribute__((aligned(16))) b;
__attribute__((aligned(16))) unsigned char c;
According to my research, __attribute__((aligned(16)))
does the same to the respective variable in the three lines above. But such a weak syntax would be unusual for C, so I am somehow mistrustful.
Returning to my original problem, I am aware that I easily could avoid the uncertainty by something like
__attribute__((aligned(16))) unsigned char a;
__attribute__((aligned(16))) unsigned char b;
or perhaps
unsigned char a __attribute__((aligned(16))),
b __attribute__((aligned(16)));
But I really would like to know whether it is sufficient to add the __attribute__
decoration once when declaring multiple variables which all should have the attribute.
Of course, that question relates to all attributes (not only the aligned
attribute).
As a bonus question, is it considered good style to add such attributes not only to the variable definitions, but also to the variable declarations (e.g. in header files)?
Yes; both
and
align
a
andb
to 16 byte boundary. gcc handles__attribute__
as part of the type (likeconst
andvolatile
modifiers) so that mixed things likeare possible too.
https://gcc.gnu.org/onlinedocs/gcc/Attribute-Syntax.html#Attribute-Syntax says:
That is why
would apply to
a
only but not tob
.In another case like
only
b
is aligned. Herefrom https://stackoverflow.com/a/31067623/5639126 applies.
To avoid all the ambiguities, it would be better to create a new type and use this. E.g.
With this example and your
gcc creates (
gcc -c
) andreadelf
shows the described alignments