Path: utzoo!mnetor!uunet!husc6!necntc!ima!haddock!karl From: karl@haddock.ISC.COM (Karl Heuer) Newsgroups: comp.lang.c Subject: Re: global data in C programming... Message-ID: <3032@haddock.ISC.COM> Date: 17 Mar 88 17:18:54 GMT References: <7506@ncoast.UUCP> Reply-To: karl@haddock.ima.isc.com (Karl Heuer) Organization: Interactive Systems, Boston Lines: 36 Keywords: global data, extern, C programming Summary: declare it N times, but define it just once In article <7506@ncoast.UUCP> btb@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@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.