# Accessing a variable from multiple files

## Recommended Posts

sj    127
Hi, I have written a logger class and now I want to create a single global instance of that class that could be accessed from any file. I've tried putting "static Logger log("filename.txt");" into the header file that contains the definition of Logger. This seems to work except that the constructor and destructor are called two times instead of just one. I wonder if this is because I tried using it in two separate files? I don't want to make Logger to be a singleton, because I also want to allow multiple instances of it. Is it possible to accomplish what I'm trying to do? I've tried using extern but have not been able to get it right (I'm also a little unsure of extern's usage). Juha

##### Share on other sites
nife    235
HPP:
extern Logger log;

CPP:
Logger log("filename.txt");

##### Share on other sites
Evil Steve    2017
extern Logger g_theLogger;
In one .cpp file:
Logger g_theLogger("filename.txt");

Alternatively, use a singleton:
As a member function:
static Logger& Get();
Logger& Logger::Get(){   static Logger theLogger("filename.txt");   return theLogger;}

Or you could use new to allocate it the first time if you wish.

##### Share on other sites
sj    127
Great, I got it working now. Thank you Evil Steve and nife (thanks also for fast replies).

Juha