Global variable C++ driving me nuts!!!!

Associate
Joined
26 Jun 2003
Posts
1,140
Location
North West
I have a variable:
int view;

and a few files:

main.cpp
main.h
file1.cpp
file1.h
file2.cpp
file2.h

Now each file needs to access the one global copy of view, so I tried putting in a global.h file that is included on each header file above. Now I get the error:

In file included from include/main.h:6,
from src/main.cpp:17:
include/globals.h:9: redefinition of `int view'
src/main.cpp:15: `int view' previously declared here
In file included from include/file1.h:9,
from include/main.h:7,
from src/main.cpp:17:
include/globals.h:9: redefinition of `int view'
include/globals.h:9: `int view' previously declared here

Ive tried loads of combinations and I cant get it to stop giving me this error!

Any ideas?
 
Associate
Joined
9 May 2005
Posts
121
Location
Yorkshire
Have you put the preprocessor code to stop it including multiple versions?

put somethings like this in the global.h

at the beginning:
Code:
#ifndef _GLOBALH_
#define _GLOBALH_
then at the end of global.h
Code:
#endif
This works most of time for me but if someone has a better way... :)
 
Permabanned
Joined
13 Jan 2005
Posts
10,708
Yup - sounds l;ike you need some include guards, as suggested.

Global variables are a Bad Thing though - you should consider encapsulating them into a singleton class.....
 
Back
Top Bottom