Reputation: 24508
I use cout and printf for my debugging. However, when i want to run a "clean" code without cout messages
i have to comment out every single one. How can i turn on/off
example:
for(int i = 0 ; i < 10 ; i++){
cout << "=======================" <<endl ;
for(int j = 0 ; j < 5 ; j++){
cout << j " " ;
int sum = i + j ; //actual work
}
}
can i compile it somehow with a some option? like this: g++ main.cpp -no_log and it does not print any couts? How do developers do it in c++?
Upvotes: 0
Views: 2437
Reputation: 11502
For a serious application one will set up a logging framework (logger can have different logging levels and you only output something if the level of a message is greater or equal than the level of your logger).
For an example of a logging framework see: Poco Logging Framework
For a quick solution:
#ifdef DEBUG
cout << "debug message" << endl;
#endif
Notice that you will have to define DEBUG
if in debugging build e.g by passing -D Debug
to the compiler command line options.
VC already comes with _DEBUG
defined (Defined when you compile with /LDd, /MDd, and /MTd.
). See: http://msdn.microsoft.com/en-us/library/b0084kay.aspx
Upvotes: 1
Reputation:
Use a macro such as
#define COUT if (0) cout
and replace every occurrence of cout
.
You can enable the logs by changing the 0 to a 1. If you substitute the 0 with the name of a global Boolean variable, you can even make this setting dynamic (run-time).
Upvotes: 2
Reputation: 8629
I would recommend using Boost logging:
The core also provides another way to disable logging. By calling the set_logging_enabled with a boolean argument one may completely disable or reenable logging, including applying filtering. Disabling logging with this method may be more benefical in terms of application performance than setting a global filter that always fails.
http://boost-log.sourceforge.net/libs/log/doc/html/log/detailed.html
Upvotes: 0
Reputation: 258648
Guard it with a debug macro:
#ifdef DEBUG_MODE
cout << "whatever";
#endif
Or wrap it in a class so you don't have to write the macro every time:
class Log
{
public:
template<typename T>
Log& operator << (const T& x)
{
#ifdef DEBUG_MODE
std::cout << x;
#endif
return *this;
}
};
Upvotes: 4