关键点
- 在main.cpp引入SetUnhandledExceptionFilter程序奔溃时生成dmp文件(代码)
- Build release时包含debug信息(图)
- Link dbghelp.lib库(图)
- Build post自动复制qt依赖库(图)
Qt捕获Crash关键代码
main.cpp
#include <QtWidgets/QApplication>
#include <QMessageBox>
#include <QDateTime>
#include <QDir>
#include <QDebug>
#include "QtCrashApplication.h"
#include "main.h"
#ifdef Q_OS_WIN
#include <Windows.h>
#include <DbgHelp.h>
#endif
#ifdef Q_OS_WIN
static LONG WINAPI exceptionCallback(struct _EXCEPTION_POINTERS* exceptionInfo)
{
QCoreApplication* app = QApplication::instance();
QString savePath = app->applicationDirPath() + "dump/";
qDebug() << "save path :" << savePath;
QDir dir(savePath);
if (!dir.exists() && !dir.mkpath(savePath)) {
app->exit(E_UNEXPECTED);
return EXCEPTION_EXECUTE_HANDLER;
}
savePath.append("assit_");
savePath.append(QDateTime::currentDateTime().toString("yyyyMMddhhmmsszzz"));
savePath.append(".dmp");
HANDLE dump = CreateFileW(savePath.toStdWString().c_str(), GENERIC_WRITE,
0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (INVALID_HANDLE_VALUE == dump) {
app->exit(E_UNEXPECTED);
return EXCEPTION_EXECUTE_HANDLER;
}
MINIDUMP_EXCEPTION_INFORMATION miniDumpExceptionInfo;
miniDumpExceptionInfo.ExceptionPointers = exceptionInfo;
miniDumpExceptionInfo.ThreadId = GetCurrentThreadId();
miniDumpExceptionInfo.ClientPointers = TRUE;
DWORD idProcess = GetCurrentProcessId();
MiniDumpWriteDump(GetCurrentProcess(), idProcess, dump,
MiniDumpNormal, &miniDumpExceptionInfo, NULL, NULL);
CloseHandle(dump);
app->exit(E_UNEXPECTED);
return EXCEPTION_EXECUTE_HANDLER;
}
#endif
int main(int argc, char* argv[])
{
QApplication a(argc, argv);
#ifdef Q_OS_WIN
SetUnhandledExceptionFilter(exceptionCallback);
#endif
QtCrashApplication w;
w.show();
return a.exec();
}
QtCrashApplication.cpp
#include "QtCrashApplication.h"
QtCrashApplication::QtCrashApplication(QWidget *parent)
: QMainWindow(parent)
{
ui.setupUi(this);
QObject::connect(ui.CrashButton, SIGNAL(clicked()), this, SLOT(crashMe()));
}
void QtCrashApplication::crashMe() {
int i = 0;
int n = 1 / i;
ui.CrashButton->setText(QString(n));
}
新建项目
配置项目
项目配置向导
项目配置向导2
编写会奔溃程序
程序运行截图
点击运行后出现异常
自动生成依赖qt库
"$(QTDIR)\bin\windeployqt.exe" "$(OutDir.TrimEnd('\'))" --$(Configuration.toLower())