3

I have a program consisting out of different modules. The modules are interconnected via function calls. E.g. State Init calls the init function of every module. It shall be possible to disable modules (exclude from compilation). The easiest way would be using preprocessor defines. But this generates massive amount of code:

#IF MODULE_XXX_COMPILE
     ret = module_func(...);
#ELSE
     ret = 0;
#ENDIF

I would like to get a macro like this:

ret = MOD_COMPILE_CALL(module_func(...));

So the macro checks if the define is 1 if yes it executes the functions else it skips the execution and returns 0. The problem is that my compiler is telling me that its not possible to use #IF in a macro. Is there a way around it?

3
  • Without seeing your macro code we are not able to help you
    – ckruczek
    Commented Mar 16, 2016 at 9:34
  • Do it the other way around. Conditionally #define MOD_COMPILE_CALL(x) to expand to either x or 0 depending on MODULE_XXX_COMPILE.
    – kaylum
    Commented Mar 16, 2016 at 9:39
  • Isn't is easier to let the build system choose between a full or a stub version of the module? That way, all the calls remain as if all modules are enabled, but the module functions do nothing when the stub is selected. Don't worry about the neglible performance cost until you can measure it.
    – user824425
    Commented Mar 16, 2016 at 9:46

3 Answers 3

6

Instead of using #if inside your macro, which will probably not work you could just take it out:

#if MODULE_XXX_COMPILE == 1
    #define MOD_COMPILE_CALL(fcall) (fcall)
#else
    #define MOD_COMPILE_CALL(fcall) (0)
#endif
0
3

Yes, it's possible.

Define IF_MOD_XXX:

#if MODULE_XXX_COMPILE
#define IF_MOD_XXX(mod_enabled, mod_disabled) mod_enabled
#else
#define IF_MOD_XXX(mod_enabled, mod_disabled) mod_disabled
#endif

Use it:

int ret = IF_MOD_XXX(module_func(), 0);
1
  • Really good answer, when default return is defined at call instead of hard writing in macro!
    – Garf365
    Commented Mar 16, 2016 at 9:44
1

Here is an example to do what you want:

#if MODULE_XXX_COMPILE == 1
    #define MOD_COMPILE_CALL(x) (x)
#else
    #define MOD_COMPILE_CALL(x) (0)
#endif

If MODULE_XXX_COMPILE is defined as 1, MOD_COMPILE_CALL(module_func(...)); expands to (module_func(...)). Otherwise, it's just 0.

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.