0

In my code, I'm using a lot of expressions like:

#if DEBUG
    printf("Some text = %d", param);
#endif

I was wondering if it is possible to change it to macro like:

DEBUG("Some text = %d", param); 

or at least to:

DEBUG("Some text =", param);

?

python
  • 198
  • 1
  • 5
  • 13
  • `#if` by itself is illegal, did you mean `#ifdef FOO` or something – M.M Nov 05 '14 at 21:20
  • @MattMcNabb It is not necessarily illegal. e.g `gcc -DDEBUG prog.c`, `gcc prog.c` both OK. – BLUEPIXY Nov 05 '14 at 21:32
  • @BLUEPIXY the grammar specification is `#if` *constant-expression* *new-line* , so that would either be a gcc bug or a gcc extension. What does gcc do with it? – M.M Nov 05 '14 at 21:35
  • @MattMcNabb The identifiers remaining after macro expansion are replaced by zero. – BLUEPIXY Nov 05 '14 at 21:41
  • @MattMcNabb see **6.10.1 Conditional inclusion 4** [n1256.pdf](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf) – BLUEPIXY Nov 05 '14 at 21:48

1 Answers1

1
#ifdef DEBUG
    #define DPRINTF(...) printf(__VA_ARGS__)
#else
    #define DPRINTF(...)
#endif

Is that good enough ?

Quentin
  • 62,093
  • 7
  • 131
  • 191
  • Are you sure this should work? http://ideone.com/JfgTMc – python Nov 05 '14 at 21:33
  • The logging function macro is `DPRINTF()`. `DEBUG` is just a constant to control the `#ifdef` conditional. – M Oehm Nov 05 '14 at 21:35
  • @python Read again : I called the macro `DPRINTF()`, since `DEBUG` usually enables/disables debug mode (as in your snippet). Of course you can change it. – Quentin Nov 05 '14 at 21:35
  • @Quentin: I'm still not sure how to use it. I tried: `#ifdef DEBUG 1 ...` but this is not printing anything then. Sorry for that stupid question but I have never used so complicated macros before. – python Nov 05 '14 at 21:41
  • Just copy-paste it and use `DPRINTF(...)`. Then you can switch the debug mode by providing `-DDEBUG` to gcc to define `DEBUG` or not. – Quentin Nov 05 '14 at 21:47
  • I'd also love to know why that downvote popped up... – Quentin Nov 05 '14 at 21:52
  • @Quentin Ok, now I've got it. Thanks :) And btw. is it possible to not use -DDEBUG flag but change it for true or false in my program (like I wanted with DEBUG 1)? – python Nov 05 '14 at 21:52
  • 1
    @python Yes you can, just `#define DEBUG /* whatever, or nothing */` somewhere, and ensure that it is visible from every `DPRINTF()` call. Comment it out to disable debugging. You can also change the `#ifdef` condition to specifically check for `true`. – Quentin Nov 05 '14 at 22:05