How to declare global variable outside a class?
Printable View
How to declare global variable outside a class?
Create a header with global definitions.
Example: my_globals.h
Code:
#ifndef MYGLOBALS #define MYGLOBALS int variable1; #endif
Include the header everywhere you want.
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.
Code:
// globalvar.h #ifndef MYGLOBALS #define MYGLOBALS extern int variable1; extern int variable2; #endif ... // globalvar.cpp implementation int variable1= 0; int variable = 0;