1

I have the following lines of code which is needed to be written across many files in a project:-

#if SOME_CHECK
    foo(x, y, z);
#endif

For this, I am planning to wrap the above 3 lines of code into a single macro like this-

#define foo(x, y, z) #if SOME_CHECK \
foo(x, y, z); \
#endif

But, this is giving me error for obvious reasons and I am unable to think of a better way to make use of the preprocessor macros to wrap those 3 lines of code. Can anyone suggest some better ways to handle the above problem?

Sankalp
  • 2,796
  • 3
  • 30
  • 43

3 Answers3

3

Why not do this?

#if SOME_CHECK
... The actual function
#else
    #define foo(x,y,z)
#endif

Whereby any occurrence of foo will be zapped then SOME_CHECK is set. Otherwise the function is called.

Ed Heal
  • 59,252
  • 17
  • 87
  • 127
  • Note that this solution comes with small side effects. You might get warnings about x, y and z not i use – eyalm Nov 08 '13 at 05:48
  • @JonathanLeffler - Corrected - Opps. -eyalm - Depends on the compiler and warning levels. If using C++ could use inline functions instead – Ed Heal Nov 08 '13 at 05:52
1

The classic way to do this would be:

foo.h

#ifndef FOO_H_INCLUDED
#define FOO_H_INCLUDED

#if SOME_CHECK
extern void foo(int x, int y, int z);
#define FOO(x, y, z) foo(x, y, z)
#else
#define FOO(x, y, z) ((void)0)
#endif

#endif /* FOO_H_INCLUDED */

Code conditionally calling foo()

#include "foo.h"

...
FOO(a, b, c);
...

When SOME_CHECK is defined to a non-zero value, then the code will call foo() with the given arguments. When SOME_CHECK is not defined, the code will expand to ((void)0) which will be ignored by the compiler.

You probably can leave the alternative definition as an empty string if you wish (instead of using ((void)0), but you'd run into problems if someone tried to use FOO() in the context of a comma operator, or a ternary operator, for example:

FOO(a, b, c), ALTEREGO(d, e f);

(x > y) ? FOO(a, b, c) : ALTEREGO(d, e, f);

In both of those, #define FOO(x, y, z) /* Nothing */ would generate syntax errors. This is not the end of the world; they're both horrid bits of code and shouldn't be encouraged. But that's a judgement call you'll have to make for your project.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
0

how about trying:

#ifdef SOME_CHECK
#define foo(x,y,z) foo(x,y,z);
#else
#define foo(x,y,z)
#endif