QT: 自定义断言;

时间:2023-03-10 03:07:28
QT:  自定义断言;

使用Qt  creator + mingw + gdb进行qt项目开发时,应用Q_ASSERT进行断言总是会出现问题:  断言失败,程序崩溃而不是停止;

采用自定义断言能完美解决该问题(方法取自于国外论坛);

/**
自定义断言
*/
#define IQS_ASSERT 2
#if IQS_ASSERT == 1
#define iQsAssert Q_ASSERT
#elif IQS_ASSERT == 2
#define iQsAssert(cond) {\
if(!(cond)) {\
qDebug("ASSERT: %s in %s (%s:%u)",#cond, Q_FUNC_INFO, __FILE__, __LINE__); \
asm("int $3");\
}\
}
#else
#define iQsAssert(cond) {}
#endif

通过修改IQS_ASSERT能切换断言方式;

注:  上面的写法只适用于调试, 如果应用于发布版本,将出现未响应的状态;

下面是我的修改方案:

/**
自定义断言
*/ #ifdef QT_NO_DEBUG
#define DEBUG_STOP
#else
#define DEBUG_STOP {asm("int $3");}
#endif #define IQS_ASSERT 2
#if IQS_ASSERT == 1
#define iQsAssert Q_ASSERT
#elif IQS_ASSERT == 2
#define iQsAssert(cond) {\
if(!(cond)) {\
qDebug("ASSERT: %s in %s (%s:%u)",#cond, Q_FUNC_INFO, __FILE__, __LINE__); \
DEBUG_STOP \
}\
}
#else
#define iQsAssert(cond) {}
#endif

通过QT_NO_DEBUG进行条件编译,当编译为release时,不进行软中断;

国外论坛: https://forum.qt.io/topic/12842/q_assert-no-longer-pauses-debugger/17