Given a struct, for instance:
struct A {
char a;
char b;
} __attribute__((packed));
I want the offset of b
(in this example, 1) in the struct to be printed at compile time - I don't want to have to run the program and call something like printf("%zu", offsetof(struct A, b));
because printing is non-trivial on my platform. I want the offset to be printed by the compiler itself, something like:
> gcc main.c
The offset of b is 1
I've tried a few approaches using #pragma message
and offsetof
, with my closest being:
#define OFFSET offsetof(struct A, b)
#define XSTR(x) STR(x)
#define STR(x) #x
#pragma message "Offset: " XSTR(OFFSET)
which just prints:
> gcc main.c
main.c:12:9: note: #pragma message: Offset: __builtin_offsetof (struct A, b)
which does not print the numeric offset. It's possible to binary-search the offset at compile time by using _Static_assert
- but my real structs are big and this can get a bit cumbersome.