Accessing a variable from multiple files
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
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:
Or you could use new to allocate it the first time if you wish.
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.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement