简体   繁体   中英

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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