3 ms·
While the C and C++ language specs don't specify the layout of bitfields, modern platforms tend to have a specified ABI which compilers follow when compiling fo
by Findecanor 5y ago
While the C and C++ language specs don't specify the layout of bitfields, modern platforms tend to have a specified ABI which compilers follow when compiling for that platform.
64-bit Linux distros and the BSDs follow the convention once set by the "C ABI for Itanium".
In that, bitfields are grouped in declaration order into container words of the same width as the bitfield's type (char, int, etc.).
Bitfields don't span multiple container words, and container words don't overlap.
On little-endian platforms, bitfields are packed LSB first, but on big-endian platforms they are packed MSB first within their container word.
Alignment rules apply only to the container words.
- ncmncm 5y agoThat is all very fine. If the instructions emitted and the instructions implemented both happen to match that, on every chip your code must run on, you got lucky.
- deleted 5y ago[deleted]
- dfox 5y agoThe point is that if you care about the resulting in-memory layout then you by definition know on what platform the code will run and what is the ABI. If you want to produce same sequence of bytes regardless of underlying platform, then you have to do it by hand with uint8_t[] buffers and explicit shifts and masks. Casting pointer to struct to char* and writing it somewhere is inherently non-portable and this gas nothing to do with bitfields and nothing to do with things like __attributte__((packed)), although both of these things are useful when you want to do that and understand the (non-)portability implications.
- ncmncm 5y agoTotally missing the point. This not about exact bit placement, which is a whole other bag of worms.