0

Code written as follows,

#define print_err(fmt, ...) \
    do { if (DEBUG_ERR) fprintf(stderr, "%s:%d:%s(): " fmt, __FILE__, \
                            __LINE__, __func__, ##__VA_ARGS__); } while (0)

I am getting error, if not define the DEBUG_ERR macro. Compilation was done using gcc 5.4.0. There is no problem if the macro DEBUG_ERR is defined.

include/tmp.h:54:18: error: ‘DEBUG_ERR’ undeclared (first use in this function)
         do { if (DEBUG_ERR) fprintf(stderr, "%s:%d:%s(): " fmt, __FILE__, \*
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
Rajeshkumar
  • 739
  • 5
  • 16

3 Answers3

2

The if instruction inside your macro is a C instruction, not a preprocessor instruction (you can't nest preprocessor instructions)

So DEBUG_ERR must be defined even if debug must not be activated. Set it to 0 and hopefully the compiler wil optimize your statement out.

What you could do instead is test the DEBUG_ERR macro outside and define empty macro if not defined:

#ifdef DEBUG_ERR
#define print_err(fmt, ...) \ do { fprintf(stderr, "%s:%d:%s(): " fmt, __FILE__, \ __LINE__, __func__, ##__VA_ARGS__); } while (0)
#else
#define print_err(fmt, ...) do {} while(0)
#endif
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
0

What you can do also is define DEBUG_ERR as another macro or not. Then you can get rid of the if in print_err

#ifdef DEBUG_ERR
#define print_err(fmt, ...) \
    do { fprintf(stderr, "%s:%d:%s(): " fmt, __FILE__, \
         __LINE__, __func__, ##__VA_ARGS__); } while (0)
#else
#define print_err(fmt, ...)
#endif
Serve Laurijssen
  • 9,266
  • 5
  • 45
  • 98
0

To make a conditional on the definition/nondefinition of a preprocessor #define, you have to use #ifdef or #if defined.

See, for example, this description of #if defined

If you want to use it in a code conditional, you can define it as 0 or 1 and then you can use it in an "if".

So you can do either:

#ifdef DEBUG_ERR
#define print_err(fmt, ...) \
            do {  fprintf(stderr, "%s:%d:%s(): " fmt, __FILE__, \
                           __LINE__, __func__, ##__VA_ARGS__); } while (0)
#else
#define print_err(fmt, ...)
#endif

Or do as you have done but define DEBUG_ERR to 1 or 0 instead of defining it/leaving it undefined.

I have generally used the first option.

Basya
  • 1,477
  • 1
  • 12
  • 22