[置顶] NO.4 使用预处理器进行调试

《c++ primer》第四版 p190

********************************************************************************************************************************************************************************************

在调试程序时,会在程序里加一些代码用来观察测试程序允许的情况。当程序调试完毕后,需要注释掉或者删除那些代码,有时候这个工作会显得略微的繁琐。

这里有一个好方法——利用预处理器来帮助调试。

下面给出代码

#include <iostream>
using std::cout;
int main (void)
{
    #ifndef NDEBUG
    cerr << "starting main"<< endl;
    #endif
    //注意sizeof()返回值的不同
    int x[10];
    int *p = x;
    cout << sizeof(x) <<" "<< sizeof(*x) << endl;
    cout << sizeof(p) <<" "<< sizeof(*p) << endl;
    return 0;
}

注意这个

#ifndef NDEBUG
cerr <<"strting main"<<endl;
#endif

下面编译执行

g++ test.cpp
./a.out

结果如下

starting main
40 4
8 4

因为NDEBUG没有定义,所以程序执行了#ifndef 和#endif 之间的代码。

我们可以通过定义NDEBUG预处理变量,来删除#ifndef #endif之间的代码。

g++ -DNDEBUG test.cpp

然后执行结果如下

./a.out
40 4
8 4

这样我们就很方便的删除了这调试的语句。


原文地址:https://www.cnblogs.com/pangblog/p/3265243.html