This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: extern question


Trevis Rothwell writes:
 > Given the files:
 > 
 > /* main.c */
 > #include <stdio.h>
 > 
 > extern void foo (void);
 > extern void bar (void);
 > 
 > extern int larry;
 > 
 > int main (void) {
 >   printf ("inside main: %d\n", larry);
 >   foo();
 >   bar();
 > 
 >   return 0;
 > }
 > 
 > /* foo.c */
 > int larry = 42;
 > 
 > extern void foo (void) {
 >   printf ("inside foo: %d\n", larry);
 >   return;
 > }
 > 
 > /* bar.c */
 > int larry;
 > 
 > extern void bar (void) {
 >   printf ("inside bar: %d\n", larry);
 >   return;
 > }
 > 
 > ...
 > 
 > Compiling and linking all of these together generates a program which
 > gives the following output:
 > 
 > inside main: 42
 > inside foo: 42
 > inside bar: 42
 > 
 > ...
 > 
 > If I add a variable definition to bar.c (so that "larry" is given a
 > value in both foo.c and bar.c) then the compiler complains that the
 > variable is defined more than once, which is true.  But, my question
 > is:  should I even be allowed to declare "larry" in both foo.c and
 > bar.c ?  If so, why is that not seen as a problem?

This is Section J.5.11 of ISO C. _Common extensions_:

"There may be more than one external definition for the identifier of
an object, with or without the use of extern ... if the definitions
disgree, or more than one is initialized, the behavior is undefined."

Andrew.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]