title: How does sizeof(struct) help provide ABI compatibility?
body: <p>Suppose a C library has to share the details of a structure with the application code and has to maintain API and ABI backward compatibility. It tries to do this by checking the size of the structure passed to it.</p>
  
  <p>Say, the following structure needs to be updated. In library version 1,</p>
  
  <pre><code>typedef struct {
      int size;
      char* x;
      int y;
  } foo;
  </code></pre>
  
  <p>In version 2 of the library, it is updated to:</p>
  
  <pre><code>typedef struct {
      int size;
      char* x;
      int y;
      int z;
  } foo_2;
  </code></pre>
  
  <p>Now, library version 2 wants to check if the application is passing the new <code>foo_2</code> or the old <code>foo</code> as an argument, <code>arg</code>, to a function. It assumes that the application has set <code>arg.size</code> to <code>sizeof(foo)</code> or <code>sizeof(foo_2)</code> and attempts to figure out whether the application code groks version 2.</p>
  
  <pre><code>if(arg.size == sizeof(foo_2)) {
      // The application groks version 2 of the library. So, arg.z is valid. 
  } else {
      // The application uses of version 1 of the library. arg.z is not valid.
  }
  </code></pre>
  
  <p>I'm wondering why this won't fail. On GCC 4.6.3, with -O3 flag, both <code>sizeof(foo)</code> and <code>sizeof(foo_2)</code> are 24. So, won't v2 library code fail to understand if the application is passing a struct of type <code>foo</code> or <code>foo_2</code>? If yes, how come this approach seems to have been used?</p>
  
  <p><a href="http://wezfurlong.org/blog/2006/dec/coding-for-coders-api-and-abi-considerations-in-an-evolving-code-base/" rel="nofollow">http://wezfurlong.org/blog/2006/dec/coding-for-coders-api-and-abi-considerations-in-an-evolving-code-base/</a></p>
  
  <p><a href="http://blogs.msdn.com/b/oldnewthing/archive/2003/12/12/56061.aspx" rel="nofollow">http://blogs.msdn.com/b/oldnewthing/archive/2003/12/12/56061.aspx</a></p>
  
  <hr>
  
  <p>Follow on question: Is there a good reason to favor the use of <code>sizeof(struct)</code> for version discrimination? As pointed out in the comments, why not use an explicit <code>version</code> member in the shared struct?</p>