Just wanted to share this code with you:
#ifndef DBGHELPER_H #include <QString> #ifndef QT_NO_DEBUG # define DEBUG_FUNC_NAME DbgHelper dbgHelper(Q_FUNC_INFO); #else # define DEBUG_FUNC_NAME #endif class DbgHelper { public: DbgHelper(const QString &t); ~DbgHelper(); private: QString txt; static int indent; static int colorIndex; int myColor; }; #endif |
#include "dbghelper.h" #ifdef DBGHELPER_USES_PRINTF #include <stdio.h> #else #include <QtDebug> #endif int DbgHelper::indent = 0; int DbgHelper::colorIndex = 0; static void DbgHelper_output(int color, int indent, const QString &prefix, const QString &funcName) { QString text = QString(4*indent, ' ')+QString(prefix+" "+funcName); if(color>=0){ text.prepend("\x1b[3"+QString::number(1+color)+"m"); text.append("\x1b[39m"); } #ifndef DBGHELPER_USES_PRINTF qDebug() << text; #else fprintf(stderr, "%s\n", qPrintable(text)); #endif } DbgHelper::DbgHelper(const QString &t) { txt = t; #ifdef NO_COLOR myColor=-1; #else myColor = colorIndex; colorIndex = (colorIndex+1) % 7; #endif DbgHelper_output(myColor, indent, "BEGIN", txt); ++indent; } DbgHelper::~DbgHelper() { --indent; DbgHelper_output(myColor, indent, "END", txt); } |
Now you can do this:
#include "dbghelper.h" #include <QtDebug> class Cls { public: Cls(){ DEBUG_FUNC_NAME } ~Cls() { DEBUG_FUNC_NAME } void method(const QString &str) { DEBUG_FUNC_NAME int x = anotherMethod(); } int anotherMethod() { DEBUG_FUNC_NAME qDebug() << "Regular output"; return 7; } }; int main(){ Cls c; c.method("foobar"); return 0; } |
And obtain a nice colorful (where ANSI escape sequences are supported) output:
BEGIN Cls::Cls() END Cls::Cls() BEGIN void Cls::method(const QString&) BEGIN int Cls::anotherMethod() Regular output END int Cls::anotherMethod() END void Cls::method(const QString&) BEGIN Cls::~Cls() END Cls::~Cls()
If you want, you can extend it to take argument values as well or print the file and line numbers where a particular method is defined.
What do you think? Do you have your own macros or classes that help you with debugging?