开发者

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 开发者_StackOverflow社区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)


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:

#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. Also, AFAIK, you can remove the 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜