I am creating a C ++ library that uses many of the functions and struct defined in the C library. To avoid porting any code to C ++, I add typical conditional preprocessing to the C header files. For example,
//my_struct.h of the C library #include <complex.h> #ifdef __cplusplus extern "C" { #endif typedef struct { double d1,d2,d3; #ifdef __cplusplus std::complex<double> z1,z2,z3; std::complex<double> *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
The implementation of alloc_my_struct() compiled in C. It simply allocates memory through malloc() and initializes the members of my_struct .
Now, when I do the following in my C ++ code,
#include "my_struct.h" ... my_struct *const ms = alloc_my_struct(2.);
I notice that *ms always has the expected memory layout, that is, any access, such as ms->z1 , is evaluated to the expected value. I find this really cool, considering that (correct me if I am wrong) the location of the memory my_struct during allocation is determined by the C compiler (in my case gcc -std=c11 ), while during access by the C ++ compiler (in my case g++ -std=c++11 ).
My question is: is this compatibility standardized? If not, is there a way around this?
NOTE I do not have enough knowledge to argue with alignment, complement and other implementation-specific features. But it should be noted that the GNU science library, which compiles in C, implements the same approach (although their struct does not contain C99 complex numbers) for use in C ++. On the other hand, I have done enough research to conclude that C ++ 11 guarantees layout compatibility between C99 double complex and std::complex<double> .