Global Variables

Global variables can be accessed throughout the entire program. This is their benefit and their drawback at the same time — code depending on global variables is innately tied to that single instance, which becomes problematic if you suddenly need multiple instances of that variable (say, you decide to add multiple monitor support to your application).

Example

global.hpp
#ifndef IG_GLOBALS_EXAMPLE_GLOBAL
#define IG_GLOBALS_EXAMPLE_GLOBAL
 
extern int global;
// This only *declares* the global variable -- in essence,
// tell the compiler that there's a variable by that name
// with that type in the program.  This does *not* initialize
// the variable, or anything like that.
 
#endif //ndef IG_GLOBALS_EXAMPLE_GLOBAL
global.cpp
#include "global.hpp"
// Including the header will do nice little things like make the
// compiler throw up a nice error if you do something stupid,
// such as mismatching the types between the header and
// the source file.
 
int global = 42;
// This is the *definition* of the global variable.  It tells the
// compiler to instantiate the global, and initialize it if it has
// a default constructor or you gave it a value.  This line
// occurs only *once* in the program.
main.cpp
#include "global.hpp"
// You need to #include the *declaration* of the variable
// in order to be able to use that variable in your code. If
// you only use the global in the same source file as you
// *define* it, you can skip writing a header entirely, since
// the definition will double as a declaration.
 
#include <cassert>
 
int main() {
    assert( global == 42 ); //should be true
}