Nyan
Nyan

Reputation: 2461

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 files. Is it legal according to C standard? Which part of standard says so? (There is no #inclusion of struct definitions.)

Upvotes: 1

Views: 1087

Answers (3)

AnT stands with Russia
AnT stands with Russia

Reputation: 320421

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.

Upvotes: 6

sje397
sje397

Reputation: 41812

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).

Upvotes: 6

phimuemue
phimuemue

Reputation: 35983

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?.

Upvotes: 1

Related Questions