Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C variable definition vs extern decleration

Tags:

c

gcc

extern

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?

like image 923
Kenneth Avatar asked Aug 24 '26 10:08

Kenneth


2 Answers

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.

like image 126
marcolz Avatar answered Aug 25 '26 23:08

marcolz


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

like image 37
Les Avatar answered Aug 26 '26 01:08

Les



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!