The global object is not available for other C ++ source files

I have an ErrorLog class that is used to write and modify log files. I would like to write it before and after major events for debugging purposes, and I want to use only one instance of the ErrorLog class for the entire application. I tried declaring the ErrorLog object global by placing

 ErrorLog exe_log; 
to the header file so that it is available to other files, but I continue to receive an error message that is already defined. Is there a way to prevent global objects?
0
c ++ scope global-variables
Aug 28 '10 at 17:42 on
source share
4 answers

You need a declaration in the header file and a definition in the source file.

foo.h:

 extern ErrorLog exe_log; // declaration (note the "extern") 

foo.cpp:

 ErrorLog exe_log; // definition 

bar.cpp:

 #include "foo.h" 
+7
Aug 28 '10 at 17:48
source share
β€” -

You should define this as in one source file and declare it in the header as:

 extern ErrorLog exe_log; 

Having said that using global variables or class instances is disapproving. You should get used to trying to avoid this as much as possible.

For such cases, a design pattern known as Singleton has been proposed, although at present many developers, for good reason , strongly discourage its use.

+1
Aug 28 '10 at 17:47
source share

I think you're looking for a Singleton Pattern . You must have a static member of type ErrorLog* in your ErrorLog class and initialize it using the create function, similar to the following:

 // .h file class ErrorLog { public: ErrorLog* create() { if (!this->log) this->log = new ErrorLog(); return this->log; } private: static ErrorLog* log; ErrorLog() {} } // .cpp file ErrorLog* ErrorLog::log = NULL; 
0
Aug 28 '10 at 17:49
source share

I don’t know about any β€œcorrect” way (at least the standard does not define one afaik). However, one good way to use global objects is to define them using a singleton pattern . In your case, this will result in a static member declaration in your ErrorLog class of type ErrorLog. Thus, the global object will not be in the global scope (which can be dangerous in some cases).

0
Aug 28 '10 at 17:49
source share



All Articles