How to declare a global variable that could be used in the entire program

c++

Question

I have a variable that I would like to use in all my classes without needing to pass it to the class constructor every time I would like to use it. How would I accomplish this in C++?

Thanks.

1
21
6/24/2017 9:09:02 AM

Accepted Answer

global.h
extern int myVar;

global.cpp
#include "global.h"
int myVar = 0;  // initialize

class1.cpp
#include "global.h"
...

class2.cpp
#include "global.h"
...

class3.cpp
#include "global.h"
...

MyVar will be known and usable in every module as a global variable. You do not have to have global.cpp. You could initialize myVar in any of the class .cpp's but I think this is cleaner for larger programs.

26
1/8/2010 5:23:06 PM

If you're not going to use the Singleton pattern as Lyndsey suggests, then at least use a global function (inside a namespace) to access the variable. This will give you more flexibily in how you manage that global entity.

// mymodule.h
namespace mynamespace // prevents polluting the global namespace
{
   extern int getGlobalVariable();
}

// mymodule.cpp
namespace mynamespace
{
   int myGlobalVariable = 42;

   int getGlobalVariable()
   {
      return myGlobalVariable;
   }
}

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon