Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are structs with preprocessor branched implementation an ODR violation?

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?

like image 918
Lorah Attkins Avatar asked Dec 23 '22 18:12

Lorah Attkins


1 Answers

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?

like image 193
Lightness Races in Orbit Avatar answered Dec 28 '22 22:12

Lightness Races in Orbit