1.调试标记
适用预处理#define定义一个或多个调试标记,在代码中把调试部分使用#ifdef 和#endif 进行管理。当程序最终调试完成后,只需要使用#undef标记,调试代码就会消失。常用的调试标记为DEBUG, 语句序列:
#define DEBUG
#ifdef DEBUG
调试代码
#endif |
2.运行期间调试标记
在程序运行期间打开和关闭调试标记。通过设置一个调试bool标记可以实现。这对命令行运行的程序更为方便。
例如下面代码
#include<iostream> #include <string> using namespace std; bool debug =false; int main(int argc,char*argv[]) { for(int i=0;i<argc;i++) if(string(argv[i])==“--debug=on“) debug = true; bool go=true; while(go) { if(debug) { 调试代码 }else {} } } |
3.把变量和表达式转换成字符串
可是使用字符串运算符来实现转换输出定义
#define PR(x) cout<<#x”=”<<x<<'/n' |
4.c语言的assert()
该宏在<assert>中,,当使用assert时候,给他个参数,即一个判读为真的表达式。预处理器产生测试该断言的代码,如果断言不为真,则发出一个错误信息告诉断言是什么以及它失败一会,程序会终止。
#include< assert> using namsapce std; int main() { int i=100; assert(i!=100); //Fails } 当调试完毕后在#include<assert>前加入#define NDEBUG即可消除红产生的代码 } |
 
|