Search code examples
cgccextern

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?


Solution

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