Kenneth
Kenneth

Reputation: 1167

C variable definition vs extern decleration

This seems like the sort of question that has already been covered but I can't seem to find out where.

I have come across a peculiar behaviour of gcc.

I file A I have the following definition:

struct SomeStruct {
  unsigned int uiVarA;
  unsigned int uiVarB;
} SomeVar;

I file B the extern decleration differs:

extern struct SomeStruct {
  unsigned char filler;
  unsigned int uiVarA;
  unsigned int uiVarB;
} SomeVar;

In fact I can make the definition be a double and the extern decleration be an int and gcc will happily compile without so much as a warning (with -Wall and -Wextra even).

I can only conclude this must mean it is perfectly legal behaviour but how it that so?

I am aware that the linker does the job of mapping the two variables but is there no errorchecking at this stage?

Upvotes: 3

Views: 108

Answers (2)

Les
Les

Reputation: 10605

From the C Spec.

6.2.7 Compatible type and composite type

2 All declarations that refer to the same object or function shall have compatible type; otherwise, the behavior is undefined.

So, it is not perfectly legal behavior in that the behavior is undefined. But that doesn't mean that your linker has the ability to check for it. It is syntactically correct (as long as each declaration is in different translation units).

Upvotes: 3

marcolz
marcolz

Reputation: 2970

Unless you include one file in the other, the compiler will not see both of your definitions.

Normally you would simply declare the struct in a header file separately and then declare variables of that type, so like:

in a.h:

struct SomeStruct {
   unsigned int uiVarA;
   unsigned int uiVarB;
}       

In a.c you could then do: struct SomeStruct SomeVar; and in b.c extern struct SomeStruct SomeVar after including a.h. Or better yet, put the extern struct in a header file and include that in both a.c and b.c.

Upvotes: 4

Related Questions