简体   繁体   English

使用宏在代码中放置#ifdef

[英]using macros to place #ifdef in the code

I am trying to do something like this 我正在尝试做这样的事情

#define VB_S #ifdef VERBOSE
#define VB_E #endif

so that in the code instead of writing 这样在代码中而不是编写

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

I can write 我会写

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

This gives me a compile time error: Stray '#' in the program. 这给了我一个编译时错误:程序中出现“#”错误。

Can anyone put light on what is the right way to do this 任何人都可以阐明什么是正确的方法

You can't put directives inside macros. 您不能将指令放入宏中。 ( # inside a macro as another signification -- it is the stringizing operator and must be followed by a parameter id -- but the restriction is older than that meaning) #在宏中作为另一个含义-它是字符串化运算符,并且必须后面跟参数id-但限制早于该含义)

You could do something like this: 您可以执行以下操作:

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


VB(cout << "foo");

Similar to Erik's response: 与Erik的回应类似:

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

Using a variadic macro has the benefit of allowing commas inside the VB() call. 使用可变参数宏的好处是允许在VB()调用内使用逗号。 Also, AFAIK, you can remove the do ... while . 另外,在AFAIK中,您可以删除do ... while

I prefer the following: 我更喜欢以下内容:

#define VERBOSE 1
// or 0, obviously

if (VERBOSE)
{
// Debug implementation
}

This is a little more readable since VB_S doesn't mean anything to the average user, but if (VERBOSE) does. 这一点更具可读性,因为VB_S对普通用户没有任何意义,但如果(VERBOSE)有意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM