Extern variables question

Walter Murray walter at hpclwjm.HP.COM
Sat Nov 18 06:18:33 AEST 1989


John Hascall writes:

>     I have been involved in a ``discussion'' over which (if any) of the
> four following pairs of modules are identical in result.  Assume that in
> each case the two modules are compiled separately and linked with:

>      int main(int argc, char **argv) {
>         void foo(void); void bar(void); foo(); bar(); return(1); }


>           module1.c             module2.c
>           -------------------   -------------------
>    (a)    int i;                int i;
>           void foo(void) {}     void bar(void) {}
> 
>    (b)    extern int i;         int i;
>           void foo(void) {}     void bar(void) {}
> 
>    (c)    extern int i;         int i = 0;
>           void foo(void) {}     void bar(void) {}
> 
>    (d)    extern int i;         extern int i;
>           void foo(void) {}     void bar(void) {}

> What is the answer and WHY?

This is something that varies depending on your compiler and linker.
In ANSI C, the answer is that all four cases are legal and produce
the same result.

> WHY?

Why not?  No rule has been violated.

The answer would be different if 'i' were actually used somewhere (other
than as part of the operand of sizeof).  Then case (a) would be illegal
(more than one "external definition" for 'i'), and case (d) would be
illegal (no "external definition" for 'i').  Cases (b) and (c) would
still be legal and have the same result.  Note that a global
declaration of the form "int i;" is called a tentative definition
and has the same effect as "int i = 0;" if it is the only declaration
for 'i' in that translation unit (module).

This whole area was a major standardization issue, and the rules
finally adopted by ANSI C try to accommodate as many existing
environments and implementations as possible.

Walter Murray
----------



More information about the Comp.lang.c mailing list