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; }
可以加入文件名、行号之类的输出,这样会更加清晰。
本文作者:Gold_stein
本文链接:https://www.cnblogs.com/smartljy/p/18395707
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步