PDA

View Full Version : How to declare global variable outside a class?



babygal
26th August 2010, 06:41
How to declare global variable outside a class?

tbscope
26th August 2010, 06:50
Create a header with global definitions.

Example: my_globals.h

#ifndef MYGLOBALS
#define MYGLOBALS

int variable1;

#endif

Include the header everywhere you want.

toutarrive
26th August 2010, 08:35
Use extern keyword to avoid allocating some memory for yours global variables every time you include your header globalvar.h in multiple files. With this keyword you only allocate them once.


// globalvar.h

#ifndef MYGLOBALS
#define MYGLOBALS

extern int variable1;
extern int variable2;

#endif

...

// globalvar.cpp implementation

int variable1= 0;
int variable = 0;