delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1994/04/01/09:31:23

Date: Fri, 1 Apr 1994 9:02:04 -0500 (EST)
From: "Chris Mr. Tangerine Man Tate" <FIXER AT FAXCSL DOT DCRT DOT NIH DOT GOV>
To: djgpp AT sun DOT soe DOT clarkson DOT edu
Subject: Re: storage allocation of global var

Wonkoo Kim wrote:

> For example, two files, main.c and test.c, both have the following line:
>
>   #include "test.h"
>
> and, a global variable is declared in test.h:
>
>   int global_var;
>
> I compiled *.c separetely and then linked them, (with -Wall compile),
> and I didn't have any warning message for double declarations.
>
> My question is, 
>
> 1. Is there no storage loss?  (i.e., Is the storage for 'global_var'
>    allocated only once and shared by both main.c and test.c?)

Apparently, in your case, the linker is combining the multiply-defined
variables of the same type and linkage into a single storage location,
assuming that you meant to refer to the same variable in both places.
This isn't exactly according to the ANSI spec, though Kernighan & Ritchie
(2nd edition) discuss the issue briefly on page 227 (section A10.2 of
the ANSI reference manual).  The behavior of GCC that you describe here
is considered a "common extension to the ANSI spec."  If you use the
-ansi flag to GCC, you should get at least a warning about it; if you
use -ansi -pedantic you should get an error. 

#define	PEDANTIC

You shouldn't do this.  Declare everything in .h files "extern," and
then have a single non-extern declaration of all of your globals.  I
personally put all of my globals into a single "globals.c" source,
but that's not always the best approach (though it does make certain
kinds of bookkeeping easier).  If you want to have variables that
only get accessed from within a given file, make sure you declare
them "static" in that file.  Better yet, program in C++, and use its
information-hiding features to handle access to shared information.

#undef PEDANTIC

(Sorry; I just had to get that off my chest.  :-)

-- Chris Tate
   fixer AT faxcsl DOT dcrt DOT nih DOT gov

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019