English 中文(简体)
Can you #define a comment in C?
原标题:

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

...
最佳回答

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

问题回答

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
", __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.

С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

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

#define CMT / ## /

but no grantees for all compilers.

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.

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"

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

In C++17 I like to use constexpr for something like this

#ifndef NDEBUG
constexpr bool DEBUG = true;
#else
constexpr bool DEBUG = false;
#endif

Then you can do

if constexpr (DEBUG) /* debug code */

The caveats are that, unlike a preprocessor macro, you are limited in scope. You can neither declare variables in one debug conditional that are accessible from another, nor can they be used at outside function scopes.

You can take advantage of if. For example,

#ifdef debug
    #define printd printf
#else 
    #define printd if (false) printf
#endif

Compiler will remove these unreachable code if you set a optimization flag like -O2. This method also useful for std::cout.

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.

I use this construct a lot:

#define DEBUG 1
#if DEBUG
#if PROG1
#define DEBUGSTR(msg...)        { printf("P1: "); printf( msg); }
#else
#define DEBUGSTR(msg...)        { printf("P2: "); printf( msg); }
#endif
#else
#define DEBUGSTR(msg...)    ((void) 0)
#endif

This way I can tell in my console which program is giving which error message... also, I can search easily for my error messages...

Personally, I don t like #defining just part of an expression...

It s been done. I don t recommend it. No time to test but the mechanism is kind of like this:

 #define printd_CAT(x) x ## x
 #ifndef DEBUG
    #define printd printd_CAT(/)
 #else
    #define printd printf
 #endif

This works if your compiler processes // comments in the compiler itself (there s no guarantee like the ANSI guarantee that there are two passes for /* comments).





相关问题
Fastest method for running a binary search on a file in C?

For example, let s say I want to find a particular word or number in a file. The contents are in sorted order (obviously). Since I want to run a binary search on the file, it seems like a real waste ...

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

Tips for debugging a made-for-linux application on windows?

I m trying to find the source of a bug I have found in an open-source application. I have managed to get a build up and running on my Windows machine, but I m having trouble finding the spot in the ...

Trying to split by two delimiters and it doesn t work - C

I wrote below code to readin line by line from stdin ex. city=Boston;city=New York;city=Chicago and then split each line by ; delimiter and print each record. Then in yet another loop I try to ...

Good, free, easy-to-use C graphics libraries? [closed]

I was wondering if there were any good free graphics libraries for C that are easy to use? It s for plotting 2d and 3d graphs and then saving to a file. It s on a Linux system and there s no gnuplot ...

Encoding, decoding an integer to a char array

Please note that this is not homework and i did search before starting this new thread. I got Store an int in a char array? I was looking for an answer but didn t get any satisfactory answer in the ...

热门标签