In a project that uses both C and C++, a .h
file contains a definition of a type. If that definition depends on whether the header is included by c
or cpp
files, am I violating the one definition rule?
// my_header.h
struct MyStruct
{
#ifdef __cplusplus
std::size_t member;
int surprise;
#else
unsigned member;
#endif
};
I know that ODR has to do with different translation units, but in "my case" won't different translation units end up having different implementations for a common struct? I've seen this in production code and initially I was wondering what is the linker doing in this case.
Any thoughts?
As long as you use one compiler (C or C++), you won't have a problem. It doesn't matter what extension the header files have.
But if you're linking together translation units from different languages, then yes you're violating the ODR.
Overall this just seems really error prone. I'd give the C++ type an entirely different name. You can use your macro to switch between the two, perhaps using the preprocessor around a typedef
?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With