Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can __attribute__ ((packed)) create a 1-bit struct when the only member is a bit-field?

I was reading through the documentation of GNU/GCC and I stopped at the description of __attribute__ ((packed)).
It says:

packed

The packed attribute specifies that a variable or structure field should have the smallest possible alignment—one byte for a variable, and one bit for a field, unless you specify a larger value with the aligned attribute.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Here is a structure in which the field x is packed, so that it immediately follows a:

struct foo
{
    char a;
    int x[2] __attribute__ ((packed));
};

I wonder how this attribute works exactly and whether this code:

struct bar
{
    char a:1 __attribute__ ((packed));
};

would create a 1-bit structure instead of 1-byte.

>Solution :

A byte is the smallest addressable unit. As such, structs can only occupy a whole number of bytes, not fractional bytes.

Any unused bits in bitfields (or more accurately, the storage units containing bitfields) become padding.

So in your example of struct bar, the size of the struct will still be 1, with 1 bit used and 7 bits unused.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading