Implement offsetof() using a compiler builtin.
Short answer: The compiler knows the layout and padding of each structure. The GCC/Clang builtin gives the member's byte offset at compile time without evaluating a null pointer.
#include <stddef.h>
#define MY_OFFSETOF(type, member) __builtin_offsetof(type, member)
struct device {
char status;
int id;
};
size_t id_offset(void)
{
return MY_OFFSETOF(struct device, id);
}
On a common ABI with 4-byte int alignment, the offset of id is 4 rather than 1. Use standard offsetof from stddef.h in portable code; the builtin is compiler-specific. Do not implement it by subtracting or dereferencing null pointers, and do not apply it to a bit-field.