Accessing a variable from multiple files

Started by
2 comments, last by sj 17 years, 12 months ago
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
Advertisement
HPP:
extern Logger log;

CPP:
Logger log("filename.txt");
Killers don't end up in jailThey end up on a high-score!
In your loggers header:
extern Logger g_theLogger;
In one .cpp file:
Logger g_theLogger("filename.txt");

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

Or you could use new to allocate it the first time if you wish.
Great, I got it working now. Thank you Evil Steve and nife (thanks also for fast replies).

Juha

This topic is closed to new replies.

Advertisement