c++ - 在 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
解决方案
我宁愿使用适当的调试器而不是这些宏,但如果你真的需要使用这些,你可以这样做:
#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 中:
推荐阅读
- javascript - ElementRef 不能与 Bsdatepicker 一起使用 Angular 8
- java - 我如何模拟 JWT.decode?
- php - Laravel 使用不带分隔符的格式获取当前日期
- laravel - 如何在 Laravel 6 中创建来自不同表名的下拉列表数据
- c# - 在更新实体中的大量记录时面临问题
- node.js - 如何解析从 Pub/sub 触发的 Cloud Function 中的 Json 有效负载
- react-native - 如何在 Expo 中使用 Cordova 插件?
- javascript - Javascript promise(Async/Await) 在 Node api 上实现
- ubuntu - HTK 32 位问题 -> apt-get install gcc-multilib -> “包 'gcc-multilib' 没有安装候选”
- python - 单击时更改 QCandlestickSet 中“蜡烛”的颜色