在C++中取消调试函数的更好方法

Better way to nullify debug functions in C++

本文关键字:更好 方法 函数 调试 C++ 取消      更新时间:2023-10-16

我的程序使用了许多#ifdef _DEBUG_ ... #endif块,以取消发布版本的调试功能。

然而,它会阻塞代码,并使代码读起来不愉快。

有更好的方法吗?

我可以想到的一种方法是通过将函数定义为空来取消它,例如:

#ifdef _DEBUG_
void foo(int bar)
{
   do_somthing();
}
#else
#define foo(a) do {; } while(0)
#endif

所以我们只有一个#ifdef _DEBUG_ ... #endif。所有调用foo()的地方,我们不必添加#ifdef _DEBUG_ ... #endif

然而,也有例外:

  1. 当调试函数有返回值时,上述策略将不起作用。例如,调用函数的代码可能是以下模式:bar = foo();
  2. 同样,当调试函数是类的成员函数形式时,上述策略将不起作用

知道吗?

把#ifdef移到函数本身中怎么样?即

// In a .h file somewhere...
inline int foo(int bar)
{
#ifdef DEBUG
    return do_something();
#else
    (void) bar;  // this is only here to prevent a compiler warning
    return 1;  // or whatever trivial value should be returned when not debugging
#endif
}

只要函数可以内联(即,只要函数体在头文件中),编译器就会在非DEBUG的情况下对其进行优化,因此这样做在非调试构建中不应该有任何额外的开销。

如果函数太大而无法正常内联,Jeremy的解决方案将不起作用,您仍然需要这两个定义。

// In .h file
#ifndef NDEBUG
int foo(int bar); // Definition in .cpp file
#else
inline int foo(int) {
    return 42;
}
#endif

注意,根据assert约定,NDEBUG是为发布版本定义的。