delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/2000/02/13/09:33:49

From: "Andrew Jones" <luminous-is AT home DOT com>
Newsgroups: comp.os.msdos.djgpp
References: <886bi1$2l0$1 AT cubacola DOT tninet DOT se>
Subject: Re: Values in header ?? (urgent)
Lines: 60
X-Priority: 3
X-MSMail-Priority: Normal
X-Newsreader: Microsoft Outlook Express 5.00.2919.6600
X-MimeOLE: Produced By Microsoft MimeOLE V5.00.2919.6600
Message-ID: <jUyp4.37954$45.2075784@news2.rdc1.on.home.com>
Date: Sun, 13 Feb 2000 14:07:11 GMT
NNTP-Posting-Host: 24.42.120.18
X-Complaints-To: abuse AT home DOT net
X-Trace: news2.rdc1.on.home.com 950450831 24.42.120.18 (Sun, 13 Feb 2000 06:07:11 PST)
NNTP-Posting-Date: Sun, 13 Feb 2000 06:07:11 PST
Organization: @Home Network Canada
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp
Reply-To: djgpp AT delorie DOT com

> Hi!
> Why canīt I declare a value in a header without get the error "multiple
> definiton" when I include the header several times? I have tried #ifndef but
> NOTHING seems to work.
>
> If the header looks like this:
> #ifndef HEADER
> #define HEADER
> bool value;
> #endif
>
> This error appear:
> Error: multiple definiton of 'value'
>
> ...when I include the header two times or if I try to compile the header.
> Can someone wise explain what's wrong? Thank you...

<grin>  I remember when I ran into this problem back in my younger days.  The
problem is that each time you include the header in a seperate source file,
it's trying to create a global boolean variable.  So you're basically creating
multiple variables of the same name.  You can't do this due to namespace
clashes (the variable has already been found in the global namespace).

What you want to do is:

// example.c

#include "example.h"

bool value = false; /* or true, or nothing if you don't want to initialize it
*/

// example.h

#ifndef __example_h_
#define __example_h_

extern bool value; /* note that you do NOT initialize the variable here */

#endif

The #ifndef/#define macros ensure that a header file is not accidently included
multiple times in the same source file, and is a good habit to get into.
Basically this declares a global variable called value, and the extern ...
makes it visible to everything outside of the translation unit it was declared
in.

This is the way it should be done.  If you have a variable in a .c file that
you don't want to make visible to everything else, you should declare it as
static:

static bool value;

This makes it possible to have a variable named value in each and every
individual source file, without them ever clashing.

AndrewJ


- Raw text -


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