4

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

单行宏如下:

#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;


}
4

2 回答 2

6

将宏包装在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 
于 2013-01-03T01:36:22.933 回答
4

如果这是用于“任意”调试代码(而不是严格记录),那么一个粗略的选择是直接#if/ #endif

#if defined(DEBUG) | defined(_DEBUG)
    #define DBG_ONLY
#endif 

...    

#ifdef DBG_ONLY
    // Blah blah blah
#endif

这绝对比@perreal 的解决方案更丑陋,但它避免了任何范围界定问题,并且适用于所有语言变体(以及我们尚未考虑的任何其他问题!)。

它也是条件代码也是事实,因此有可能严重不同步(因为编译器并不总是检查它)。但这也适用于宏观解决方案。

还有一个优势;在一个不错的 IDE(例如 Eclipse CDT)中,您的调试代码将以不同的方式突出显示。

于 2013-01-03T01:35:14.740 回答