Can you #define a comment in C?

22,407

Solution 1

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).

Solution 2

A common trick is to do this:

#ifdef DEBUG
  #define OUTPUT(x) printf x
#else
  #define OUTPUT(x)
#endif

#include <stdio.h>
int main(void)
{   
  OUTPUT(("%s line %i\n", __FILE__, __LINE__));

  return 0;
}

This way you have the whole power of printf() available to you, but you have to put up with the double brackets to make the macro work.

The point of the double brackets is this: you need one set to indicate that it's a macro call, but you can't have an indeterminate number of arguments in a macro in C89. However, by putting the arguments in their own set of brackets they get interpreted as a single argument. When the macro is expanded when DEBUG is defined, the replacement text is the word printf followed by the singl argument, which is actually several items in brackets. The brackets then get interpreted as the brackets needed in the printf function call, so it all works out.

Solution 3

С99 way:

#ifdef DEBUG
    #define printd(...) printf(__VA_ARGS__)
#else
    #define printd(...)
#endif

Well, this one doesn't require C99 but assumes compiler has optimization turned on for release version:

#ifdef DEBUG
    #define printd printf
#else
    #define printd if (1) {} else printf
#endif

Solution 4

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

#define CMT / ## /

but no grantees for all compilers.

Solution 5

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.

Share:
22,407
Admin
Author by

Admin

Updated on July 01, 2020

Comments

  • Admin
    Admin almost 4 years

    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(...)
    
    ...