Duplicate struct definition in different source file
foo.c:
struct foo {
int a;
};
bar.c:
struct foo {
char *s;
double x,y;
};
The struct
definitions are only in .c 开发者_Go百科files. Is it legal according to C standard? Which part of standard says so? (There is no #inclusion of struct
definitions.)
The code is perfectly legal C. You might run into problems with debuggers (mistaking one type for another and attempting to display one as another), but it is fine from the language point of view.
There's no part of the standard that would directly say that this is legal. Rather, there's no part of the standard that says it is illegal.
Something like this would be illegal in C++, since C++ extends the concept of linkage to classes and non-local in C++ classes always have external linkage.
Section 6.2.1-4 of the C99 standard indicates that it is legal as both are declared in different scopes (each having file scope extending from their definition to the end of the translation unit, i.e. the file).
If they do not "know" of each other (i.e. via #include
or something), that should be no problem. If they do, you might have a look at How to resolve two structures with the same name?.
精彩评论