C++简单日志/debug调试信息输出

C++简单日志/debug调试信息输出

在写一些简单的小项目,或者算法题的时候,没有必要使用spdlog、log4cpp这样专门的日志库,但是如果把所有的调试语句都用

#ifdef DEBUG
...
#endif

这样的语句块包围,就太麻烦了,我们可以用一个宏/函数来替代这些每处都不得不插入的语句块。

1.最简单的宏

#ifdef DEBUG
#define DEBUG_LOG(x) std::cout << x << std::endl;
#else
#define DEBUG_LOG(x)
#endif

只能输出最简单的信息

DEBUG_LOG("This is a debug message");

2.类似的C++写法

#include <iostream>

#ifdef DEBUG
#define DEBUG_STREAM std::cout
#else
#define DEBUG_STREAM if (false) std::cout
#endif

这种写法更加灵活,能够输出更多信息

DEBUG_STREAM << "Debug information" << std::endl;

3.内联函数

inline void debug_log(const std::string& msg) {
#ifdef DEBUG
    std::cout << msg << std::endl;
#endif
}

虽然看起来更高级,但是它的用法和第一种一样十分受限

debug_log("This is a debug message");

4.对2.的纯C实现

#include <stdio.h>
#include <stdarg.h>

// 定义一个调试输出的宏
#ifdef DEBUG
    #define DEBUG_LOG(fmt, ...) \
        do { \
            fprintf(stderr, "DEBUG: " fmt "\n", ##__VA_ARGS__); \
        } while (0)
#else
    #define DEBUG_LOG(fmt, ...) \
        do { } while (0)
#endif

int main() {
    int x = 42;
    const char* str = "example";

    // 使用调试宏
    DEBUG_LOG("This is a debug message");
    DEBUG_LOG("Value of x: %d", x);
    DEBUG_LOG("This is a string: %s", str);

    return 0;
}

可以加入文件名、行号之类的输出,这样会更加清晰。

posted @ 2024-09-04 02:43  Gold_stein  阅读(21)  评论(0编辑  收藏  举报