Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Path: utzoo!mnetor!seismo!husc6!rutgers!okstate!uokmax!rmtodd From: rmtodd@uokmax.UUCP (Richard Michael Todd) Newsgroups: comp.os.minix Subject: Global variables (was Re: More on sh/shar Message-ID: <587@uokmax.UUCP> Date: Thu, 4-Jun-87 23:34:45 EDT Article-I.D.: uokmax.587 Posted: Thu Jun 4 23:34:45 1987 Date-Received: Tue, 9-Jun-87 04:29:13 EDT References: <1643@encore.UUCP> <581@uokmax.UUCP> <498@sortac.UUCP> Organization: University of Oklahoma, Norman, OK Lines: 60 Summary: Clarification of previous posting In article <498@sortac.UUCP>, fdg@sortac.UUCP (Fred Gant) writes: > In article <581@uokmax.UUCP> rmtodd@uokmax.UUCP (Richard Michael Todd) writes: > >In article <1643@encore.UUCP>, paradis@encore.UUCP (Jim Paradis) writes: > >file foo.c: > > int a; > >... > > > >file bar.c: > > int a; > >... > daily and can comment on that. In your example, "int a" is not global in > either case. It is in fact local to the file that declares it. To be > global, it must be declared in a header file, such as sh.h, or be declared > outside of the function. An example would be I guess I wasn't clear enough in my original statement. I meant that the two "int a" definitions were in two separate files, each one being a global definition (i.e. outside any function). Here's a full example of the kind of code I was referring to: ------------------ File #1: foo.c -------------------- int a; main() { a = 5; printf("%d\n",a); bar(); printf("%d\n",a); } ---------------- File #2: bar.c ---------------------- int a; bar() { a = 7; } ---------------- end -------------- In this example, the 'a's in both files are global variables. On UNIX systems, compiling with "cc foo.c bar.c" will succeed and in the resulting program both modules, when referring to 'a' refer to the same memory location, thus the program will print out: 5 7 On non-UNIX systems, the linker will complain about multiple definitions of the symbol a. Note that the functions 'main' and 'bar' above do not have to declare within the function body that 'a' is extern, as you did in your example code: > int a, b; /* These are global. */ > main() > { > extern int a, b; /* a & b are globals used by main */ > int c, x; /* c, x, & y are local to main */ It's probably a good practice to do so, since it warns the reader that the function uses these global variables, but I know of no compiler that requires the extern as long as the function appears in the source file after the definition of the variables. > This posting is not meant to be critical. I am attempting to clear up a > point of confusion. Ditto. ___________________________________________________________________________ Richard Todd USSnail:820 Annie Court,Norman OK 73069 UUCP: {allegra!cbosgd|ihnp4}!okstate!uokmax!rmtodd