title: Memory-layout compatibility between C and C++
body: <p>I'm building a <strong>C++</strong> library which uses many functions and <code>struct</code>'s defined in a <strong>C</strong> library. To avoid porting any code to C++, I add the typical conditional preprocessing to the C header files. For example,</p>
  
  <pre><code>//my_struct.h of the C library
  #include &lt;complex.h&gt;
  
  #ifdef __cplusplus
  extern "C" {
  #endif
  
  typedef struct {
    double d1,d2,d3;
  #ifdef __cplusplus
    std::complex&lt;double&gt; z1,z2,z3;
    std::complex&lt;double&gt; *pz;
  #else
    double complex z1,z2,z3;
    double complex *pz;
  #endif
    int i,j,k;
  } my_struct;
  
  //Memory allocating + initialization function
  my_struct *
  alloc_my_struct(double);
  
  #ifdef __cplusplus
  }
  #endif
  </code></pre>
  
  <p>The implementation of <code>alloc_my_struct()</code> is compiled in <strong>C</strong>. It simply allocates memory via <code>malloc()</code> and initializes members of <code>my_struct</code>. </p>
  
  <p>Now when I do the following in my <strong>C++</strong> code,</p>
  
  <pre><code>#include "my_struct.h"
  ...
    my_struct *const ms = alloc_my_struct(2.);
  </code></pre>
  
  <p>I notice that <code>*ms</code> always have the expected memory layout, i.e., any access such as <code>ms-&gt;z1</code> evaluates to the expected value. I find this really cool considering that (correct me if I'm wrong) the memory layout of <code>my_struct</code> during allocation is decided by the C compiler (in my case <code>gcc -std=c11</code>), while during access by the C++ compiler (in my case <code>g++ -std=c++11</code>).</p>
  
  <p>My question is : Is this compatibility standardized? If not, is there any way around it?</p>
  
  <p><strong>NOTE</strong> : I don't have enough knowledge to argue against alignment, padding, and other implementation-defined specifics. But it is noteworthy that the GNU scientific library, which is C-compiled, is implementing the same approach (although their <code>struct</code>s do not involve C99 complex numbers) for use in C++. On the other hand, I've done sufficient research to conclude that C++11 guarantees layout compatibility between C99 <code>double complex</code> and <code>std::complex&lt;double&gt;</code>.</p>