Home > database >  Why can't gcc reduce the alignment of a struct to be lesser than that of one of its individual
Why can't gcc reduce the alignment of a struct to be lesser than that of one of its individual

Time:12-28

I have a struct definition employee that instantiates monica. The struct looks like this

struct __attribute__((aligned(2))) employee {
    int salary; // 4 bytes
    int age; // 4 bytes
} monica;

As you can see, I have forced the alignment of the struct to be 2 but gcc does not set the alignment of the struct to 2, nor does it throw an error. I tried to print the alignment of the struct using the alignof macro(include <stdalign.h>) which returns 4 as the alignment of the struct. Why can't gcc set the alignment of a struct to value that is less than the largest alignment of one of its fields.

I tried to reproduce the issue by additionally adding a pointer as a field in the struct. On adding the pointer as a field, I noticed that gcc does not allow me to reduce the alignment below 8 using __attribute__((aligned(x))).

GCC allows me to set the alignment of the struct to 1 by using __attribute__((packed)) but it still does not allow me to set the alignment to 1 by using __attribute__((aligned(1))). Why is this happening?

gcc x86 v7.1.1

CodePudding user response:

The GCC documentation says:

… When used on a struct, or struct member, the aligned attribute can only increase the alignment; in order to decrease it, the packed attribute must be specified as well…

That is from the GCC 11.2 documentation. You can check older documentation. There is none for 7.1 at that site; it jumps from 6.5 to 7.5, but I expect it is the same in this regard.

  • Related