C++调试帮助
assert断言
头文件
#include<cassert>
格式
assert(表达式);
assert可用于在调试或测试程序时对程序运行环境进行判断,或者执行其它的一些辅助判断操作,比如辅助调试,帮助调试信息,如果assert里面的表达式返回0(false),程序会终止运行,如果表达式返回1(true),程序会什么也不做,接着执行后面的语句
#include<cassert>
#include<iostream>
using namespace std;
int main(){
cout<<"I will goto the assert sentence"<<endl;
assert(0);
cout<<"I will exit successfully!"<<endl;
return 0;
}
Assertion failed: 0, file D:/ClionProject/C++Learn/main.cpp, line 9
I will goto the assert sentence
如果条件改成1的话,其结果为
I will goto the assert sentence
I will exit successfully!
观看assert的源码,他是依赖一个NDEBUG
的预处理宏定义的,如果NDEBUG
已定义,assert啥也不干,如果没有定义,assert才会发挥作用,比如
#define NDEBUG // 注意 NDEBUG的定义一定要在导入cassert头文件之前
#include<cassert>
#include<iostream>
using namespace std;
int main(){
cout<<"I will goto the assert sentence"<<endl;
assert(0);
cout<<"I will exit successfully!"<<endl;
return 0;
}
I will goto the assert sentence
I will exit successfully!
assert依赖于NDEBUG宏定义的原因在于cassert头文件对assert的定义中,如下
#ifdef NDEBUG
#define assert(_Expression) ((void)0) // 如果定义了NDEBUG,那么于assert宏定义相关量的宏函数什么也不做
#else /* !defined (NDEBUG) */
#if defined(_UNICODE) || defined(UNICODE)
#define assert(_Expression) \
(void) \
((!!(_Expression)) || \
(_wassert(_CRT_WIDE(#_Expression),_CRT_WIDE(__FILE__),__LINE__),0))
#else /* not unicode */
#define assert(_Expression) \
(void) \
((!!(_Expression)) || \
(_assert(#_Expression,__FILE__,__LINE__),0))
#endif /* _UNICODE||UNICODE */
#endif /* !defined (NDEBUG) */
C++编译器定义的帮助编译选项
__func__
: 当前调试函数的函数名的字符变量
__FILE__
: 存放文件名的字符串字面值
__LINE__
: 存放当前行号的整型字面值
__TIME__
: 存放文件编译时间的字符串字面值
__DATE__
: 存放文件编译日期的字符串字面值
可以使用这些常量在错误的时候输出详细的错误信息
#include<iostream>
using namespace std;
int main(){
cerr<<"Error: "<<__FILE__<<
"\nIn function: "<<__func__<<
"\nAt line: "<<__LINE__<<
"\nCompiled On: "<<__DATE__<<
"\nat: "<<__TIME__<<endl;
return 0;
}
Error: D:/ClionProject/C++Learn/main.cpp
In function: main
At line: 9
Compiled On: Jan 4 2022
at: 00:06:33