Path: utzoo!utgpu!watmath!iuvax!purdue!tut.cis.ohio-state.edu!giza.cis.ohio-state.edu!cml
From: cml@giza.cis.ohio-state.edu (Christopher Lott)
Newsgroups: comp.lang.c
Subject: question about scope & linkage
Keywords: scope, linkage
Message-ID: <57257@tut.cis.ohio-state.edu>
Date: 10 Aug 89 17:05:40 GMT
Reply-To: Christopher Lott 
Distribution: na
Organization: The Ohio State University Dept of Computer & Information Science
Lines: 53


Hi,

I am asking about the scope and declaration of a variable; I have
read K&Rv2, p. 227-228, Scope and Linkage, but can't seem to dig out
the answer.  (what is a 'translation unit' ??)

In the 2 files below, a variable ("twice") is declared, and has space allocated
for it (i think) in both files.  However, the linker does not complain about
a multiply-defined symbol, and the program works just as if one of the
symbols had been prefixed by an "extern" keyword.  As far as I can tell,
what I am doing below is incorrect, but would like to know what is happening
to make it appear to work correctly.

/* text from one.c */
int twice;

main()
{
  twice = 23;
   
  printf("value of twice is %d\n", twice);
  printf("calling function two.\n");
  two();
  printf("value of twice is %d\n", twice);
  printf ("all done.\n");
  return(0);
}

/* text from two.c */
int twice;      /* <- not declared extern */

int two()
{
   printf("value of twice is %d\n", twice);
   printf("resetting twice\n");
   twice = 83;
   return(0);
}

To test this, put the following program text into two files (one.c & two.c),
then type "cc -o one one.c two.c".  No makefile, sorry.

This question cropped up when I noticed that an object was being declared
in a header file ("int j;") and that header file was included by many files.

If the answer is just painfully obvious :-), please email, and I'll repost.
Thanks in advance!

chris...
-=-
cml@cis.ohio-state.edu        Computer Science Dept, OSU          614-292-1826
 or:  ...!{att,pyramid,killer}!osu-cis!cml