The following declaration adds several statements to compile in a C ++ file. The definition is included in C and C ++ files.
PC-Lint reports error 114: inconsistent structure declaration for the 'Rect' tag, but I'm sure it is safe.
I am compiling with Visual Studio 2008.
edit - adding an explanation that I sent to my client
Regarding the Rect problem; As you know, the structure of the same size in C and C ++ eliminates the suspicion of "undefined behavior".
Undefined behavior occurs if the actual location of the fields in the data structure depends on compilation.
You should think about all access to the member variable, as ultimately to the pointer calculated by the pointer to the beginning of the storage of the object plus the offset depending on what is in this structure.
Packing and data alignment settings affect the offset value.
The compiler is allowed to reorder types for optimal access - undefined behavior assumes that it is only because you declared two members in a specific order that they are actually stored in that order. The only thing that guarantees the declaration order is initialization, copying and destruction order.
However, when you talk about compiling C and C ++ of a given structure within the same compiler, with the same offset settings, the probability of the actual reordering is actually zero.
So the only thing we need to worry about is any difference in field offset.
For a structure containing 4 simple short integers, just confirming that version C and version C ++ are the same size, ensures that their offsets are all the same. To be more careful, we can also check that the size of the structure = 4 * sizeof (short).
I think itβs worth adding these checks, but as soon as this is done, there is no need to reorganize the code, since you will need to use separate types in C and C ++ (or move functions used to free functions).
struct Rect { short top; short left; short bottom; short right; #ifdef __cplusplus Rect(short _top=0, short _left=0, short _bottom=0, short _right=0) : top(_top), left(_left), bottom(_bottom), right(_right) {} #ifdef _WINNT_