Alex Rivera | Logout

Use #ifdefs and #define to optionally turn a function call into a comment

Asked 2009-02-13T18:01:24.470
16

Is it possible to do something like this

#ifdef SOMETHING
#define foo //
#else
#define foo MyFunction
#endif

The idea is that if SOMETHING is defined, then calls to foo(...) become comments (or something that doesn't get evaluated or compiled), otherwise it becomes a call to MyFunction.

I've seen __noop used, but I don't believe I can use that.

EDIT(s):

I don't think I can really use a macro here, because MyFunction takes a variable number of arguments.

Also, I'd like to make it so the arguments are NOT evaluated! (So doing something like commenting out the body of MyFunction doesn't really give me what I need, as the arguments will still be evaluated)

Edit
Report

4 Answers

2

If, in the case you don't want foo called, you define it as:

void foo() {}

any calls to foo() should be optimized way.

answered 2009-02-13T19:01:47.120
2

What about something along these lines:

#ifdef NDEBUG
#define DEBUG(STATEMENT) ((void)0)
#else
#define DEBUG(STATEMENT) (STATEMENT)
#endif

You would use it like this to log debugging messages:

DEBUG(puts("compile with -DNDEBUG and I'm gone"));

A non-generic version for formatted output with additional debugging information using C99 variadic macros and the __func__ identifier could look like this:

#ifdef NDEBUG
#define Dprintf(FORMAT, ...) ((void)0)
#define Dputs(MSG) ((void)0)
#else
#define Dprintf(FORMAT, ...) \
    fprintf(stderr, "%s() in %s, line %i: " FORMAT "\n", \
        __func__, __FILE__, __LINE__, __VA_ARGS__)
#define Dputs(MSG) Dprintf("%s", MSG)
#endif

Here's how you'd use these macros:

Dprintf("count = %i", count);
Dputs("checkpoint passed");
answered 2009-02-13T19:08:18.150
1
#ifdef SOMETHING
#define foo sizeof
#else
#define foo MyFunction
#endif

I'm assuming that foo is a printf style function? Anyways, this won't work with a zero parameter function, but if that were the case, you would already know what to do. If you really want to be anal you can use (void)sizeof but that's probably unnecessary.

answered 2009-02-13T19:12:08.717
0

What about surrounding each call to myFunction with

#ifdef SOMETHING
myFunction(...);
#endif

?

answered 2009-02-13T20:42:30.217

Your Answer