C++调试帮助

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值