global data in C programming...

Ed Nather nather at ut-sally.UUCP
Fri Mar 18 06:16:41 AEST 1988


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.

I mailed a few copies of an earlier version that did not handle struct{} 
definitions properly, but didn't keep a list of customers.  If anyone wants
a copy of the program I'll mail it on request.  I use it both under Unix
and with the MSC and Turbo C compilers under MS-DOS.
-- 
Ed Nather
Astronomy Dept, U of Texas @ Austin
{allegra,ihnp4}!{noao,ut-sally}!utastro!nather
nather at astro.AS.UTEXAS.EDU



More information about the Comp.lang.c mailing list