question about scope & linkage
Christopher Lott
cml at giza.cis.ohio-state.edu
Fri Aug 11 03:05:40 AEST 1989
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 at cis.ohio-state.edu Computer Science Dept, OSU 614-292-1826
or: ...!{att,pyramid,killer}!osu-cis!cml <standard disclaimers>
More information about the Comp.lang.c
mailing list