C++ debugging macro


Debugging is a must when coding, regardless of how big or complex a project is. And althought there are tons of debugging tools out there, most are overpowered for my needs or simply introduce unnecessary code  even when in the release version.

API


Configuration

  • _DEBUG

Defining "_DEBUG" enables global debugging. Most IDEs automatically define this for the debugging compilation. If debugging is disabled, no extra code will be generated in the release version. The final footprint will be the same as if Debug.h were never included, but without the need to remove all debugging symbols in the source-code.

  • GLOBAL_DEBUG_LEVEL

This established the minimum local debug level. This means for example, that if "WARNING" is established as global level, "INFO" messages will not be printed, but "WARNING" or "ALERT" messages will. The different debugging levels will be explained later.

  • DEBUG_OUTPUT_STREAM

This allows the user to determine where the debuggin stream will be directed to. By default it is set to "std::cout", but it could also be "std::cer" or "std::clog" for example.

API

  • DEBUG_THIS_FILE

By calling this macro, the file which invokes it will be added to the debug list. This becomes really handy when trying to debug several files, and at a given moment you want to disable debugging on only a few of them. Thus, the need to manually comment out all debug entries inside the code is eliminated.
  • DEBUG(level,message)

This is the actual debugging macro. It accepts a debug level and a stream compatible message. That means that any stream compatible class can be printed as a debug message. The use of the "<< operator" is also valid inside the message field.

Debug levels

  • EMERG: system is unusable.
  • ALERT: action must be taken immediately.
  • CRIT: critical conditions. Will cause future instability.
  • ERR: something has failed, but system can continue.
  • WARNING: warn that something is not as expected.
  • NOTICE: harmless yet significant.
  • INFO: informational message.
  • DEBUG: least priority debug level.

Example of use


#include "Debug.hpp"
int main ()
{
    // ENABLE DEBUG MESSAGES FOR THIS FILE
    DEBUG_THIS_FILE;

    // TRY SOME VARIABLES...
    int         i = 5;
    float        d = 1.12f;       
    const char*     message = "Hello";

    // DEBUG MESSAGE WITH "INFO" PRIORTY
    DEBUG(INFO, message << " World! " << i << " " << d);
    DEBUG(NOTICE, "Debugging is quite useful");
    return 0;
}

The result of executing this code will return:
INFO -> test_debug.cpp(13) : Hello World! 5 1.12
NOTICE -> test_debug.cpp(14) : Debugging is quite useful

Code


No comments :

Post a Comment