global data in C programming... (another way)

MH Cox cox at bentley.UUCP
Sat Mar 19 05:35:34 AEST 1988


In article <10780 at ut-sally.UUCP> nather at ut-sally.UUCP writes:
>In article <3032 at haddock.ISC.COM>, karl at haddock.ISC.COM (Karl Heuer) writes:
>> In article <7506 at ncoast.UUCP> btb at ncoast.UUCP (Brad Banko) writes:
>> >i thought that you just create a header file containing the global data
>> >declarations and then #include it into each of your source files, but
>> >when i try this (using Mark Williams C on an Atari ST), I get
>> >a "symbol redefined" message from the linker.
>> 
>> Yes.  After the preprocessing phase is through, what you have is a set of
>> source files each of which contains "int i, j;".  Although this is accepted by
>> some implementations, it is not portable.
>> 
>> $ Another popular style, which I do not recommend, is to have x.h contain
>> "global int i, j;" where "global" is a macro defined with a null expansion in
>> extern.c but expanding to "extern" for everyone else.
>
>I find that this, too, has limitations, since pre-initialized definitions don't
>work.  I finally solved the problem (to my satisfaction anyway) by writing a
>program I call "tglob" which takes the "master" set of global definitions,
>and turns it into a second file with "extern" inserted in the right places,
>and with definitions removed.  It creates a file called "sglob" which can
>then be #included in all files except main(), which #includes the definitions.
>
>This way, if I change anything in the gloabl definition file, I needn't also
>remember to change it in the other file.  I was ALWAYS making that mistake.
>I use "make" and include the dependency that re-creates "sglob" whenever the
>global definition file has been changed.

A better way (my opinion) would be to have one file, e.g. globals.c or in
main.c, with all the initialized definitions.  Then create a header
file with all the "extern" declarations without the initializations.
Include this in all your files, INCLUDING the globals.c or main.c.  The{
compiler will then catch any errors of the type:

globals.h:

extern int an_extern_int;


globals.c:

long an_extern_int = 0;		/* wrong type */


A second suggestion is to put all the extern global declarations be
put into one header file.  That makes it easy to "grep" all the files
in the directory to determine which ones access global variables (the
compiler should warn you about files that access global variables but
don't include the header file).

-- 

==========================================================================
Michael H. Cox			ARPA:  cox at garage.nj.att.com
AT&T Bell Labs			UUCP:  ihnp4!bentley!cox
184 Liberty Corner Road		COMPU$ERVE:  76525,3703
Rm 3N-D04
Warren, NJ  07060
(201) 580-8622
==========================================================================



More information about the Comp.lang.c mailing list