Perhaps I am misunderstanding something regarding the nature of the "packed" attribute, but it is my understanding that the below struct should pack to 16 bytes, rather than the normally padded 24 bytes. I can verify that the packed attribute is being applied (in general) as I have another struct defined in the same header file that is packed down from 16 bytes to 10 bytes. Is there any reason why the compiler would ignore the attribute without indicating via a warning?
To clarify, when I say that it does not appear to be packing, I am basing that off of the output of sizeof(foo) which returns 24 rather then the expected 16. The code in question is within a simple/crude custom kernel with very limited tools at the moment, so I have been relying on basic debugging via printing to screen.
I am using GCC 10.3.0 (on ubuntu).
typedef struct {
uint16_t m1;
uint16_t m2;
uint8_t m3;
uint8_t m4;
uint16_t m5;
uint32_t m6;
uint32_t m7;
}__attribute__((packed)) foo;
CodePudding user response:
As pointed out by paddy, the issue was an incorrect type definition for uint64_t
which was resulting in an extra 4 bytes per, and the 2 of them in the struct resulted in the extra 8 bytes.
CodePudding user response:
A cautionary note: while __attribute__((packed))
is defined by GCC, this is an implementation defined extension, and not part of the standard C language.
As such, while this should work as intended with GCC (or GCC derivatives), it will not necessarily work on any other compiler - therefore, if you are relying on the packing, you need to make sure that it is packing as you expect it.