dimanche 2 juin 2019

Why does a struct declaration violate the ODR in C++?

I am trying to get the compiler to react to some code that I believe does not violate the one-definition-rule in C++. Inside a header file, I have two declarations: one for a struct and one function, like this:

struct TestStruct {
    int a;
    double d;
};
int k();

Then I intentionally include the header file twice in another file with main() in it, to see what happens.

To my surprise, the compiler complains about multiple definitions for the struct. I was expecting the compiler not to raise any multiplicity error at all since both the struct and function have pure declarations.

It is only after I put the struct in a header-guard that the compiler stops complaining. But, there is no memory allocated for the struct. It is not a definition. Then why is the compiler mad?

Aucun commentaire:

Enregistrer un commentaire