title: Opaque types allocatable on stack in C
body: <p>When designing a C interface, it is common to let into the public interface (<code>.h</code>) only what needs to be known by the user program.</p>
  
  <p>Hence for example, the inner components of structures should remain hidden if the user program does not need to know them. This is indeed good practice, as the content and behavior of the struct could change in the future, without affecting the interface.</p>
  
  <p>A great way to achieve that objective is to use incomplete types.</p>
  
  <p><code>typedef struct foo opaqueType;
  </code></p>
  
  <p>Now an interface using only pointers to <code>opaqueType</code> can be built, without the user program ever needing to know the inner working of <code>struct foo</code>.</p>
  
  <p>But sometimes, it can be required to allocate such structure statically, typically on stack, for performance and memory fragmentation issues. Obviously, with above construction, <code>opaqueType</code> is incomplete, so its size is unknown, so it cannot be statically allocated.</p>
  
  <p>A work around is to allocate a "shell type", such as :</p>
  
  <p><code>typedef struct { int faketable[8]; } opaqueType;
  </code></p>
  
  <p>Above construction enforces a size and an alignment, but doesn't go farther into describing what the structure really contains. So it matches the objective of keeping the type "opaque".</p>
  
  <p>It mostly works. But in one circumstance (GCC 4.4), the compiler complains that it breaks strict-aliasing, and it generates buggy binary.</p>
  
  <p>Now, I've read a ton of things about strict aliasing, so I guess I understand now what it means.</p>
  
  <p>The question is : is there a way to define an opaque type which can nonetheless be allocated on stack, and without breaking strict aliasing rule ?</p>
  
  <p>Note that I've attempted the <a href="http://cellperformance.beyond3d.com/articles/2006/06/understanding-strict-aliasing.html" rel="noreferrer">union method described in this excellent article</a> but it still generates the same warning.</p>
  
  <p>Note also that visual, clang and gcc 4.6 and later don't complain and work fine with this construction.</p>
  
  <p><em>[Edit]</em> Information complement :</p>
  
  <p>According to tests, the problem only happens in the following circumstances :</p>
  
  <ul>
  <li>Private and public type different. I'm casting the public type to private inside the <code>.c</code> file. It doesn't matter apparently if they are part of the same union. It doesn't matter if the public type contains <code>char</code>.</li>
  <li>If all operations on private type are just reads, there's no problem. Only writes cause problems.</li>
  <li>I also suspect that <em>only functions which are automatically inlined</em> get into trouble.</li>
  <li>Problem only happens on gcc 4.4 at -O3 setting. -O2 is fine.</li>
  </ul>
  
  <p>Finally, my target is C90. Maybe C99 if there really is no choice.</p>