Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I set a debug mode in c++

Tags:

c++

I would like to set a debug mode so that it prints the log statements only if the debug mode is on. For example if I have code like this

printf("something \n");
.
.
.
perror("something \n");

It only works if the debug flag is on.. I don't want to use "if" statements. I think there is a clever way to do this using #define or something..

Thank is advance..

like image 460
codereviewanskquestions Avatar asked Dec 03 '22 08:12

codereviewanskquestions


2 Answers

#ifdef _DEBUG // or #ifndef NDEBUG
#define LOG_MSG(...) printf(__VA_ARGS__) // Or simply LOG_MSG(msg) printf(msg)
#else
#define LOG_MSG(...)                     // Or LOG_MSG(msg)
#endif

On non-Debug built LOG_MSG would yeild to nothing. Instead of defining it with raw printf, you can have your custom logging-function, or class-method to be called.

like image 77
Ajay Avatar answered Dec 30 '22 11:12

Ajay


Without going in to specific libraries or solutions, generally people make a logger class or function, and a single debug flag. The debug function checks this flag before calling printf or cout. Then in the rest of your code you simply call your debug function / method.

Here's an example:

class MyDebugger
{
    private:
        bool m_debug;

    public:
        MyDebugger();
        void setDebug(bool debug);
        void debug(const char* message);
};

MyDebugger::MyDebugger()
{
    m_debug = false;
}

void MyDebugger::setDebug(bool debug)
{
    m_debug = debug;
}

void MyDebugger::debug(const char* message)
{
    if(m_debug)
    {
        cout << message << endl;
    }
}

int main(int argc, char** argv)
{
    MyDebugger debugger;
    debugger.debug("This won't be shown");
    debugger.setDebug(true);
    debugger.debug("But this will");

    return 0;
}

of course this is an incredibly naive implementation. In real logger classes there are many levels for finer-grained control of how much detail gets printed (levels like error, warning, info, and debug to differentiate the importance of the message). They might also let you log to files as well as stdout. Still this should give you a general idea.

like image 30
Chris Eberle Avatar answered Dec 30 '22 11:12

Chris Eberle