• Advertisement
Sign in to follow this  

Accessing a variable from multiple files

This topic is 4325 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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 this post


Link to post
Share on other sites
Advertisement
HPP:
extern Logger log;

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

Share this post


Link to post
Share on other sites
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.

Share this post


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

Juha

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement