C ++ accesses a global integer of the class header file

advertisements

I have a header file that declares a class, and I want this class to access an integer that has been declared in the main cpp C++ file (i.e. another file than the class' one). I have been searching on Google and found nothing relevant. How can I do this?


Move the integer in main.cpp into a function, make it static there, have the function return a reference to it and put the function into a header file of its own which the class header file (or implementation file, if appropriate) includes.

integer.h:

#ifndef INTEGER_H // use some better, longer name here
#define INTEGER_H

int &Integer();

#endif

integer.cpp:

#include "integer.h"

int &Integer()
{
  static int i = 0;
  return i;
}

Access the integer like this:

int x = Integer(); // copy

Integer() = 123; // assign