delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1999/07/30/15:25:47

Date: Fri, 30 Jul 1999 13:22:00 +0200
From: Hans-Bernhard Broeker <broeker AT physik DOT rwth-aachen DOT de>
Message-Id: <199907301122.NAA06734@acp3bf.physik.rwth-aachen.de>
To: star_traveler4 AT hotmail DOT com
Cc: djgpp AT delorie DOT com
Subject: Re: Global vars in C++
Newsgroups: comp.os.msdos.djgpp
Organization: RWTH Aachen, III. physikalisches Institut B
X-Newsreader: TIN [version 1.2 PL2]
Reply-To: djgpp AT delorie DOT com

In article <37a15553 DOT 9035233 AT news DOT sasol DOT com> you wrote:

> I have a global variable,  which I defined in a header file.  

This sentence alone already describes the problem, nice and crisp.
You should never *define* any non-inlined function or variable in a
header file. Header files are for declarations, not for definitions.

See below for the necessary changes:

> Johann.h:
> #ifndef _JOHANN_H_
> #define _JOHANN_H_
>    int TheValue;

make that

     extern int TheValue;

The 'extern' keyword turns this from an uninitialized definition (a
special case kept for backwards compatibily with pre-1990 C compilers,
mainly) into a declaration of 'TheValue'.

> #endif


> Johann.c:
> #include <stdio.h>
> #include "johann.h"

insert

   int TheValue;

here.

> void DoTest();

> int main()
> {
>    TheValue = 25;
>    DoTest();
>    return 0;
> }


> Johann2.c:

> #include <stdio.h>
> #include "johann.h"

> void DoTest()
> {
>    printf("The value is: %d\n",TheValue);
> }

--
Hans-Bernhard Broeker (broeker AT physik DOT rwth-aachen DOT de)
Even if all the snow were burnt, ashes would remain.


- Raw text -


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