使用宏将#ifdef放在代码中

时间:2011-04-15 16:31:40

标签: c++ syntax macros syntax-error

我正在尝试做这样的事情

#define VB_S #ifdef VERBOSE
#define VB_E #endif

这样在代码中而不是写

#ifdef VERBOSE
    cout << "XYZ" << endl;
#endif

我可以写

VB_S  
    cout << "XYZ" << endl; 
VB_E

这给了我一个编译时错误:程序中的Stray'#'。

任何人都可以说明正确的方法吗

4 个答案:

答案 0 :(得分:6)

您不能将指令放在宏中。 (#在宏内部作为另一个表示 - 它是字符串化运算符,后面必须跟一个参数id - 但限制比那个意义更早了)

答案 1 :(得分:3)

你可以这样做:

#ifdef VERBOSE
#define VB(x) x
#else
#define VB(x) do { } while (false)
#endif


VB(cout << "foo");

答案 2 :(得分:2)

与Erik的回应相似:

#ifdef VERBOSE
#define VB(...) __VA_ARGS__
#else
#define VB(...) /* nothing */
#endif

使用variadic macro可以在VB()调用中允许使用逗号。此外,AFAIK,您可以删除do ... while

答案 3 :(得分:2)

我更喜欢以下内容:

#define VERBOSE 1
// or 0, obviously

if (VERBOSE)
{
// Debug implementation
}

这有点可读性,因为VB_S对普通用户没有任何意义,但是如果(VERBOSE)那么。