首页 > 解决方案 > 在 C++ 中调试

问题描述

我遇到了这个代码片段。你能解释一下如何在程序中使用这个调试吗?

#ifdef TESTING 
#define DEBUG fprintf(stderr, "====TESTING====\n") 
#define VALUE(x) cerr << "The value of " << #x << " is " << x << endl 
#define debug(...) fprintf(stderr, __VA_ARGS__) 
#else 
#define DEBUG 
#define VALUE(x) 
#define debug(...) 
#endif 

标签: c++debugging

解决方案


我宁愿使用适当的调试器而不是这些宏,但如果你真的需要使用这些,你可以这样做:

#include <iostream>

using namespace std; // better remove this and change the macro with cerr and endl instead
#define TESTING

#ifdef TESTING 
#define DEBUG fprintf(stderr, "====TESTING====\n") 
#define VALUE(x) cerr << "The value of " << #x << " is " << x << endl 
#define debug(...) fprintf(stderr, __VA_ARGS__) 
#else 
#define DEBUG 
#define VALUE(x) 
#define debug(...) 
#endif 

int main(int argc, char **argv) {
    int a = 100;
    DEBUG; // prints "====TESTING===="
    VALUE(a); // prints "The value of a is 100"
    debug("%d + %d = %d", 1, 2, 1 + 2); // prints "1 + 2 = 3"
    return 0;
}

这将为您提供以下输出:

====TESTING====
The value of a is 100
1 + 2 = 3

如果你删除#define TESTING,你不会得到任何输出,所以你可以根据你是否“测试”来删除/设置它。

或者,通常可以使用构建系统/IDE 提供这样的定义,其中它可以根据上下文自动设置/重置。例如在 Visual Studio 中:

在此处输入图像描述


推荐阅读