调试代码块的宏

时间:2013-01-03 01:33:03

标签: c++

我正在尝试创建一个宏,只有在它是调试版本时才会执行代码块。我已设法只在启用调试时才执行一行,但我无法弄清楚如何执行整个代码块。

单行宏如下:

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


}

2 个答案:

答案 0 :(得分: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 

答案 1 :(得分:4)

如果这是针对“任意”调试代码(而不是严格记录),那么一个原始选项是直截了当的#if / #endif

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

...    

#ifdef DBG_ONLY
    // Blah blah blah
#endif

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

它也是条件代码,因此可能会严重失去同步(因为编译器并不总是检查它)。但宏观解决方案也是如此。

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

相关问题