Correct or Not or Old-fashioned or Bug

++Don; mccrady at torolab6.vnet.ibm.com
Wed May 22 04:07:26 AEST 1991


> From: grimlok at hubcap.clemson.edu (Mike Percy)
>
>                                               ... I've never liked
> having to remeber to put #define EXTERN or some such in my code.  I've
> found it easiest to confine my global data to two files:
> globals.h
>   extern int foo;
>   extern double bar;
>   /* and so on, declaring all global variables */
>
> and
> globals.c
>   int foo;
>   double bar;
>   /* rest of the definitions */
>
> Since I've started doing this, I've not had any problems related to
> global data.  One problem is on certain segmented machines, in certain
> compilers memory models, I take a hit because of the segment
> placement.
>
> Comments?

Splitting the declarations off from the definitions of variables
introduced the possibility of nasty pitfalls, where somebody decides
to change the type in the .h file, and forgets to change it in
the .c file.  Example:

     ----- globals.h ------------
       extern int    foo;
       extern double bar;
     ----------------------------

     ------ globals.c -----------
       short foo;
       float bar;
     ----------------------------

Some linkers won't catch this, and any stores into foo or bar
will probably whomp some other data.  I prefer the EXTERN approach
which you seem to dread, because it lets you DEFINE and DECLARE
objects at the same time.

     ------ globals.h -----------
        #ifdef MAIN
          #define EXTERN
          #define INIT(x)    = x
        #else
          #define EXTERN extern
          #define INIT(x)
        #endif

        EXTERN int foo    INIT(5);
        EXTERN double bar INIT(3.14);
     ----------------------------

     ------ globals.c -----------
       #define MAIN
       #include "globals.h"
     ----------------------------

++Don;



More information about the Comp.lang.c mailing list