Sign in to follow this  

Accessing a variable from multiple files

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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this