調試技術

這裏,呈現一些有用提示,以幫助您調試基於 Qt 的軟件。

為調試配置 Qt

configuring Qt for installation, it is possible to ensure that it is built to include debug symbols that can make it easier to track bugs in applications and libraries. However, on some platforms, building Qt in debug mode will cause applications to be larger than desirable.

在 macOS 和 Xcode 中調試

采用/不用框架調試

The basic stuff you need to know about debug libraries and frameworks is found at developer.apple.com in: Apple 技術注意事項 TN2124 .

When you build Qt, frameworks are built by default, and inside the framework you will find both a release and a debug version (e.g., QtCore and QtCore_debug). If you pass the -no-framework flag when you build Qt, two dylibs are built for each Qt library (e.g., libQtCore.4.dylib and libQtCore_debug.4.dylib).

What happens when you link depends on whether you use frameworks or not. We don't see a compelling reason to recommend one over the other.

采用框架:

Since the release and debug libraries are inside the framework, the app is simply linked against the framework. Then when you run in the debugger, you will get either the release version or the debug version, depending on whether you set DYLD_IMAGE_SUFFIX . If you don't set it, you get the release version by default (i.e., non _debug). If you set DYLD_IMAGE_SUFFIX=_debug , you get the debug version.

不用框架:

When you tell qmake to generate a Makefile with the debug config, it will link against the _debug version of the libraries and generate debug symbols for the app. Running this program in GDB will then work like running GDB on other platforms, and you will be able to trace inside Qt.

由 Qt 識彆的命令行選項

When you run a Qt application, you can specify several command-line options that can help with debugging. These are recognized by QApplication .

選項 描述
-nograb The application should never grab the mouse or the keyboard . This option is set by default when the program is running in the gdb debugger under Linux.
-dograb 忽略任何隱式 (或明確) -nograb . -dograb wins over -nograb even when -nograb is last on the command line.

由 Qt 識彆的環境變量

At runtime, a Qt application recognizes many environment variables, some of which can be helpful for debugging:

變量 描述
QT_DEBUG_PLUGINS Set to a non-zero value to make Qt print out diagnostic information about the each (C++) plugin it tries to load.
QML_IMPORT_TRACE Set to a non-zero value to make QML print out diagnostic information from the import loading mechanism.
QT_HASH_SEED 設為整數值以禁用 QHash and QSet using a new random ordering for each application run, which in some cases might make testing and debugging difficult.

警告和調試消息

Qt includes global macros for writing out warning and debug text. You can use them for the following purposes:

  • qDebug () is used for writing custom debug output.
  • qInfo () is used for informational messages.
  • qWarning () is used to report warnings and recoverable errors in your application.
  • qCritical () is used for writing critical error messages and reporting system errors.
  • qFatal () is used for writing fatal error messages shortly before exiting.

若包括 <QtDebug> 頭文件, qDebug() 宏也可以用作輸齣流。例如:

qDebug() << "Widget" << widget << "at position" << widget->pos();
					

這些宏的 Qt 實現會打印到 stderr output under Unix/X11 and macOS. With Windows, if it is a console application, the text is sent to console; otherwise, it is sent to the debugger.

By default, only the message is printed. You can include additional information by setting the QT_MESSAGE_PATTERN 環境變量。例如:

QT_MESSAGE_PATTERN="[%{type}] %{appname} (%{file}:%{line}) - %{message}"
					

The format is documented in qSetMessagePattern (). You can also install your own message handler using qInstallMessageHandler ().

QT_FATAL_WARNINGS 環境變量有設置, qWarning () exits after printing the warning message. This makes it easy to obtain a backtrace in the debugger.

qDebug (), qInfo (),和 qWarning () are debugging tools. They can be compiled away by defining QT_NO_DEBUG_OUTPUT , QT_NO_INFO_OUTPUT ,或 QT_NO_WARNING_OUTPUT 在編譯期間。

The debugging functions QObject::dumpObjectTree() and QObject::dumpObjectInfo() are often useful when an application looks or acts strangely. More useful if you use 對象名稱 than not, but often useful even without names.

提供 qDebug() 流運算符支持

You can implement the stream operator used by qDebug () to provide debugging support for your classes. The class that implements the stream is QDebug 。使用 QDebugStateSaver to temporarily save the formatting options of the stream. Use nospace() and QTextStream 操作符 to further customize the formatting.

這裏是錶示 2D 坐標類的範例。

QDebug operator<<(QDebug dbg, const Coordinate &c)
{
    QDebugStateSaver saver(dbg);
    dbg.nospace() << "(" << c.x() << ", " << c.y() << ")";
    return dbg;
}
					

Integration of custom types with Qt's meta-object system is covered in more depth in the 創建自定義 Qt 類型 文檔。

調試宏

頭文件 <QtGlobal> 包含瞭一些調試宏和 #define

3 個重要宏是:

  • Q_ASSERT (cond), where cond is a boolean expression, writes the warning "ASSERT: ' cond ' in file xyz.cpp, line 234" and exits if cond 為 false。
  • Q_ASSERT_X (cond, where, what), where cond is a boolean expression, where a location, and what a message, writes the warning: "ASSERT failure in where : ' what ', file xyz.cpp, line 234" and exits if cond 為 false。
  • Q_CHECK_PTR (ptr), where ptr is a pointer. Writes the warning "In file xyz.cpp, line 234: Out of memory" and exits if ptr 為 0。

這些宏很有用,為檢測程序錯誤,如像這樣:

char *alloc(int size)
{
    Q_ASSERT(size > 0);
    char *ptr = new char[size];
    Q_CHECK_PTR(ptr);
    return ptr;
}
					

Q_ASSERT (), Q_ASSERT_X (),和 Q_CHECK_PTR () expand to nothing if QT_NO_DEBUG is defined during compilation. For this reason, the arguments to these macro should not have any side-effects. Here is an incorrect usage of Q_CHECK_PTR ():

char *alloc(int size)
{
    char *ptr;
    Q_CHECK_PTR(ptr = new char[size]);  // WRONG
    return ptr;
}
					

If this code is compiled with QT_NO_DEBUG defined, the code in the Q_CHECK_PTR () expression is not executed and alloc returns an uninitialized pointer.

The Qt library contains hundreds of internal checks that will print warning messages when a programming error is detected. We therefore recommend that you use a debug version of Qt when developing Qt-based software.

常見 Bug

There is one bug that is so common that it deserves mention here: If you include the Q_OBJECT macro in a class declaration and run the meta-object compiler ( moc ), but forget to link the moc -generated object code into your executable, you will get very confusing error messages. Any link error complaining about a lack of vtbl , _vtbl , __vtbl or similar is likely to be a result of this problem.