0

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

ERJAN
  • 23,696
  • 23
  • 72
  • 146

4 Answers4

4

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;
    }
};
Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
2

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

1

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

Sebastian Hoffmann
  • 11,127
  • 7
  • 49
  • 77
0

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

reectrix
  • 7,999
  • 20
  • 53
  • 81