c++ debug 神器 dbg-macro
c++ debug 神器 dbg-macro
dbg-macro 是一个 c++ 调试宏,用于简化调试过程。它以非常简洁的方式打印变量名、值、和类型等信息,便于快速定位问题,不过虽然 dbg-macro 对调试非常有帮助,但它也可能对程序性能产生影响。因此,建议仅在调试时使用它,并在发布产品时移除或禁用这些调试宏。。
特点
- 简单易用: 使用 dbg(变量) 的方式即可打印变量的名称和值,极大简化了调试信息的打印。
- 类型安全: 它是基于 c++ 的模板和宏功能实现的,可以保证类型安全。
- 丰富的信息: 不仅打印变量的值,还可以显示变量的类型,甚至是表达式的值和类型。
- 灵活性: 可以很容易地启用或禁用 dbg-macro,而不需要从代码中删除或注释调试语句。
仓库地址
1
2
# 仓库地址
https://github.com/sharkdp/dbg-macro
使用
使用 dbg() 宏来打印变量名和值。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <cstdint>
#include <vector>
#include "dbg.h"
// You can use "dbg(..)" in expressions:
int32_t factorial(int32_t n) {
if (dbg(n <= 1)) {
return dbg(1);
} else {
return dbg(n * factorial(n - 1));
}
}
int main() {
std::string message = "hello";
dbg(message); // [example.cpp:15 (main)] message = "hello" (std::string)
const int32_t a = 2;
const int32_t b = dbg(3 * a) + 1; // [example.cpp:18 (main)] 3 * a = 6 (int32_t)
std::vector<int32_t> numbers{b, 13, 42};
dbg(numbers); // [example.cpp:21 (main)] numbers = {7, 13, 42} (std::vector<int32_t>)
dbg("this line is executed"); // [example.cpp:23 (main)] this line is executed
factorial(4);
return 0;
}
输出:
1
2
3
4
5
6
7
8
9
10
11
12
[debug.cpp:16 (main)] message = "hello" (std::string)
[debug.cpp:20 (main)] 3 * a = 6 (int32_t)
[debug.cpp:23 (main)] numbers = {7, 13, 42} (std::vector<int32_t>)
[debug.cpp:26 (main)] this line is executed
[debug.cpp:7 (factorial)] n <= 1 = false (bool)
[debug.cpp:7 (factorial)] n <= 1 = false (bool)
[debug.cpp:7 (factorial)] n <= 1 = false (bool)
[debug.cpp:7 (factorial)] n <= 1 = true (bool)
[debug.cpp:8 (factorial)] 1 = 1 (int32_t)
[debug.cpp:10 (factorial)] n * factorial(n - 1) = 2 (int32_t)
[debug.cpp:10 (factorial)] n * factorial(n - 1) = 6 (int32_t)
[debug.cpp:10 (factorial)] n * factorial(n - 1) = 24 (int32_t)
本文由作者按照 CC BY 4.0 进行授权