现在的位置: 首页 > 综合 > 正文

Qt程序在Debug模式下跟踪Q_ASSERT断言

2014年09月05日 ⁄ 综合 ⁄ 共 1542字 ⁄ 字号 评论关闭

一般情况下,Qt程序在Debug模式下碰到Q_ASSERT断言就会崩溃,无法跟踪到Call Stack进行调试,特别是Q_ASSERT在Qt代码内部,如QVector越界等情况,这让人很头疼。为此,Qt提供了一个全局函数用于捕获这类断言:

Q_CORE_EXPORT QtMsgHandler qInstallMsgHandler(QtMsgHandler);

Qt文档是这样解释的:

QtMsgHandler qInstallMsgHandler ( QtMsgHandler handler )
Installs a Qt message handler which has been defined previously. Returns a pointer to the previous message handler (which may be 0).

The message handler is a function that prints out debug messages, warnings, critical and fatal error messages. The Qt library (debug mode) contains hundreds of warning messages that are printed when internal errors (usually invalid function arguments) occur.
Qt built in release mode also contains such warnings unless QT_NO_WARNING_OUTPUT and/or QT_NO_DEBUG_OUTPUT have been set during compilation. If you implement your own message handler, you get total control of these messages.

The default message handler prints the message to the standard output under X11 or to the debugger under Windows. If it is a fatal message, the application aborts immediately.

Only one message handler can be defined, since this is usually done on an application-wide basis to control debug output.

To restore the message handler, call qInstallMsgHandler(0).

调用方式:

 #include <qapplication.h>
 #include <stdio.h>
 #include <stdlib.h>

 void myMessageOutput(QtMsgType type, const char *msg)
 {
     switch (type) {
     case QtDebugMsg:
         fprintf(stderr, "Debug: %s\n", msg);
         break;
     case QtWarningMsg:
         fprintf(stderr, "Warning: %s\n", msg);
         break;
     case QtCriticalMsg:
         fprintf(stderr, "Critical: %s\n", msg);
         break;
     case QtFatalMsg:
         fprintf(stderr, "Fatal: %s\n", msg);
         abort();        // 在这里产生中断
     }
 }

 int main(int argc, char **argv)
 {
     qInstallMsgHandler(myMessageOutput);
     QApplication app(argc, argv);
     ...
     return app.exec();
 }

抱歉!评论已关闭.