Path: utzoo!yunexus!ists!jarvis.csri.toronto.edu!mailrus!cs.utexas.edu!rice!uw-beaver!Teknowledge.COM!unix!hplabs!hp-ses!hpcuhb!hpcllla!hpclisp!hpclwjm!walter From: walter@hpclwjm.HP.COM (Walter Murray) Newsgroups: comp.lang.c Subject: Re: Extern variables question Message-ID: <660066@hpclwjm.HP.COM> Date: 17 Nov 89 19:18:33 GMT Article-I.D.: hpclwjm.660066 References: <1958@atanasoff.cs.iastate.edu> Organization: Hewlett-Packard Calif. Language Lab Lines: 49 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 ----------