title: How can I print the offset of a struct member at compile time?
body: <p>Given a struct, for instance:</p>
  <pre><code>struct A {
      char a;
      char b;
  } __attribute__((packed));
  </code></pre>
  <p>I want the offset of <code>b</code> (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 <code>printf(&quot;%zu&quot;, offsetof(struct A, b));</code> because printing is non-trivial on my platform. I want the offset to be printed by the compiler itself, something like:</p>
  <pre><code>&gt; gcc main.c
  The offset of b is 1
  </code></pre>
  <hr />
  <p>I've tried a few approaches using <code>#pragma message</code> and <code>offsetof</code>, with my closest being:</p>
  <pre><code>#define OFFSET offsetof(struct A, b)
  #define XSTR(x) STR(x)
  #define STR(x) #x
  
  #pragma message &quot;Offset: &quot; XSTR(OFFSET)
  </code></pre>
  <p>which just prints:</p>
  <pre><code>&gt; gcc main.c
  main.c:12:9: note: #pragma message: Offset: __builtin_offsetof (struct A, b)
  </code></pre>
  <p>which does not print the numeric offset. It's possible to binary-search the offset at compile time by using <code>_Static_assert</code> - but my real structs are big and this can get a bit cumbersome.</p>