So, say I have the following C++ header, testheader.h:
struct mystruct
{
struct myinnerstruct
{
int x;
} astruct;
};
struct myinnerstruct
{
int x;
};
and the following C++ source, test.cpp:
#include "testheader.h"
using namespace std;
int main()
{
return 0;
}
g++ gives no issues during compile/link.
Now, if I have the same header, but instead of the C++ source, a C source file test.c:
#include "testheader.h"
int main()
{
return 0;
}
And I compile with gcc, I get the following error:
error: redefinition of struct myinnerstruct
So, I gather that the scope of the C version is the translation unit, and the C++ version is block scoped? Can someone confirm this is the case, and maybe give me a reason of why it makes sense? I’m doing some mixing of C and C++ code, and this is giving me quite a bit of trouble.
Any insight is greatly appreciated. Thanks!
In C nested structs do not actually live in their parents scope. However in C++ they do-
teststruct::innerstructis a different type toinnerstruct. This is to improve encapsulation in C++ code. Without this rule, no two types in the same namespace could define a nestediteratorclass, for example, which would be extremely bad.C treats structs in plenty of other very silly ways, so it’s no surprise that they did the wrong thing here. However, C does not otherwise allow type scoping and having a sane rule here would have introduced many additional concepts to the language- ultimately, it would have required the introduction of
namespaces, which for some reason was never done.