global data in C programming...
Karl Heuer
karl at haddock.ISC.COM
Fri Mar 18 03:18:54 AEST 1988
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.
"extern int i, j;" is a declaration; "int i, j;" is a definition. Each object
must have exactly one definition. The best$ way to do this is to change your
header file to use the "extern" keyword, and pick one source file (or make a
new one) to contain the definitions. Thus:
x.h:
extern int i, j;
x.c:
#include "x.h"
xyz() { ... i = ... }
extern.c:
#include "x.h"
int i, j;
If you want them to be initialized to non-zero values, put the initializers in
extern.c ("int i=3, j=4;"). (Actually, some implementations seem to require
the initializers anyway, to distinguish a definition from a declaration; so
you might want to add them even if they're zero.)
Karl W. Z. Heuer (ima!haddock!karl or karl at haddock.isc.com), The Walking Lint
________
$ 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.
More information about the Comp.lang.c
mailing list