gpt4 book ai didi

c++ - 代码块的调试宏

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:15:05 24 4
gpt4 key购买 nike

我正在尝试创建一个仅在调试版本时才执行代码块的宏。我设法制作了一个仅在启用调试时才执行一行的程序,但我无法弄清楚如何执行整个代码块。

一行宏如下:

#include <iostream>

//error checking
#if defined(DEBUG) | defined(_DEBUG)
#ifndef DBG_ONLY
#define DBG_ONLY(x) (x)
#endif
#else
#ifndef DBG_ONLY
#define DBG_ONLY(x)
#endif
#endif



int main () {

DBG_ONLY(std::cout << "yar" << std::endl);
return 0;


}

最佳答案

将宏包装在 do-while 循环中,这样您就可以避免在条件语句中使用宏时出现问题,例如 if (cond) DBG_ONLY(i++; j--;)。它还为仅调试声明创建了一个新范围:

#if defined(DEBUG) | defined(_DEBUG)
#ifndef DBG_ONLY
#define DBG_ONLY(x) do { x } while (0)
#endif
#else
#ifndef DBG_ONLY
#define DBG_ONLY(x)
#endif
#endif

int main () {
DBG_ONLY(
std::cout << "yar" << std::endl;
std::cout << "yar" << std::endl;
std::cout << "yar" << std::endl;
std::cout << "yar" << std::endl;
);
return 0;
}

如果你有像 int i,j 这样的语句,这将失败。为此,我想我们需要一个可变参数宏:

#if defined(DEBUG) | defined(_DEBUG)
#ifndef DBG_ONLY
#define DBG_ONLY(...) do { __VA_ARGS__; } while (0)
#endif
#else
#ifndef DBG_ONLY
#define DBG_ONLY(...)
#endif
#endif

关于c++ - 代码块的调试宏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14131925/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com