Can you #define a comment in C?

2019-03-11 17:57发布

I'm trying to do a debug system but it seems not to work.

What I wanted to accomplish is something like this:

#ifndef DEBUG
    #define printd //
#else
    #define printd printf
#endif

Is there a way to do that? I have lots of debug messages and I won't like to do:

if (DEBUG)
    printf(...)

code

if (DEBUG)
    printf(...)

...

12条回答
疯言疯语
2楼-- · 2019-03-11 18:25

The standard way is to use

#ifndef DEBUG
    #define printd(fmt, ...)  do { } while(0)
#else
    #define printd(fmt, ...) printf(fmt, __VA_ARGS__)
#endif

That way, when you add a semi-colon on the end, it does what you want. As there is no operation the compiler will compile out the "do...while"

查看更多
倾城 Initia
3楼-- · 2019-03-11 18:28

You can put all your debug call in a function, let call it printf_debug and put the DEBUG inside this function. The compiler will optimize the empty function.

查看更多
甜甜的少女心
4楼-- · 2019-03-11 18:28

Untested: Edit: Tested, using it by myself by now :)

#define DEBUG 1
#define printd(fmt,...) if(DEBUG)printf(fmt, __VA_ARGS__)

requires you to not only define DEBUG but also give it a non-zer0 value.

Appendix: Also works well with std::cout

查看更多
Rolldiameter
5楼-- · 2019-03-11 18:29

As noted by McKay, you will run into problems if you simply try to replace printd with //. Instead, you could use variadric macros to replace printd with a function that does nothing as in the following.

#ifndef DEBUG
    #define printd(...) do_nothing()
#else
    #define printd(...) printf(__VA_ARGS__)
#endif

void do_nothing() { ; }

Using a debugger like GDB might help too, but sometimes a quick printf is enough.

查看更多
地球回转人心会变
6楼-- · 2019-03-11 18:29

No, you can't. Comments are removed from the code before any processing of preprocessing directives begin. For this reason you can't include comment into a macro.

Also, any attempts to "form" a comment later by using any macro trickery are not guaranteed to work. The compiler is not required to recognize "late" comments as comments.

The best way to implement what you want is to use macros with variable arguments in C99 (or, maybe, using the compiler extensions).

查看更多
Ridiculous、
7楼-- · 2019-03-11 18:30

On some compilers (including MS VS2010) this will work,

#define CMT / ## /

but no grantees for all compilers.

查看更多
登录 后发表回答