Re: accessing variables from more than one .cpp file

From: John Harrison (john_andronicus_at_hotmail.com)
Date: 10/09/04


Date: Fri, 8 Oct 2004 23:29:44 +0100


"scott" <scottamillard@hotmail.com> wrote in message
news:ck73qu$s6s$1@news5.svr.pol.co.uk...
> hi, sorry if this has been adressed some where elss. if it has plz can you
> point me to it and ill go read it.
>
> any way, i want to declare some variables with in a header file. lets say
> int i;
>
> i then want to be able to acess that variable from multipul .cpp files
> where
> I can read it and also change the value. i would like to hold it in a
> struct or a class eventualy but i can't even get it to work on its own at
> min, so i thought id start off simple and ask how i do it just like what i
> described above.
>
> any help would be grate,
>
> thx scott
>

Put this in the header file

extern int i;

Put this in *one* .cpp file

int i;

Include the header file in every .cpp file where you need to use it.

What goes in the header file is called a declaration, what goes in the one
.cpp file is called a definition. You can have as many declarations as you
like but you must have only have one definition. This is the One Definition
Rule. Understanding the difference between declarations and definitions is
an important C++ concept to master.

BTW i is a fantastically bad name for a global variable.

john



Relevant Pages

  • HIDE 1.0.7 now available for HLA
    ... which uses the wscan.exe program to extract windows constants and external declarations from the w.hhf header file to create a more compact version to include in programs. ... This is an early experimental version which requires some manual work to get all the symbols referenced indireclty through the windows header file. ... -option to auto-complete common HLA structure keywords -1 click/key jump to declarations -debug mode and debug window to display output. ...
    (alt.lang.asm)
  • Re: Novice - Advice required
    ... > a seperate .cpp file (or header file?) and then whenever I want to ... int XYX::doTask ...
    (microsoft.public.vc.language)
  • Re: Header files question
    ... keyword) in a header file which you include where needed. ... So Nils, what you are saying? ... Declarations in the header file? ... You have a fundamental misapprehension in your usage of header ...
    (comp.lang.c)
  • Re: <Help> Simple Pause Needed.
    ... In a 'real' program you might put the declarations ... in a header file ... copy-paste is a nice easy way to do the forward declaration. ... Let's see (from Borland online help): ...
    (comp.lang.cpp)
  • Re: Suppose: All code in header files?
    ... > in the source file not in the header file. ... the only includes that should be in a header file are those ... If you're making declarations or function prototypes in your implementation ... The purpose of the header file is to declare the interface to the ...
    (comp.lang.cpp)