问题
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?
回答1:
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
回答2:
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);
回答3:
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
.
来源:https://stackoverflow.com/questions/36031581/skipping-function-call-if-not-defined