cmacros

In C is it possible to write a macro function to do a #ifdef check on a #define thats passed in?


I want to do something like this for many parameters that are passed in through "-DPARAM_NAME=x" during compile time:

#define CHECK_PARAM (PARAM_NAME,DEF_VALUE) \ 
   Pseudo code : 
#ifdef PARAM_NAME \ 
return PARAM_NAME \
#else  \
return DEF_VALUE \
#endif  

That's to return either the value passed in through PARAM_NAME=x during compile time, or the DEFAULT_VALUE if nothing is passed in.

Is this do-able through macro expansion or other techniques?


Solution

  • In C is it possible to write a macro function to do a #ifdef check on a #define thats passed in?

    No.

    Preprocessor directives cannot be recognized in macro replacement lists because they must not be preceded by anything other than whitespace on their line -- after splicing lines. A macro's replacement list is necessarily preceded at least by #define and a macro name. Moreover, preprocessor directives are recognized before macro expansion is performed, so even if a macro expands to text that, expressed directly, would have been taken to include a preprocessing directive, the expansion is not taken as containing preprocessing directives.

    Possibly you just want to provide conditional macro definitions, like so:

    #if !defined(PARAM1)
    #define PARAM1 DEF_VALUE1
    #endif
    
    #if !defined(PARAM2)
    #define PARAM2 DEF_VALUE2
    #endif
    
    // ...
    

    Then just use PARAM1, PARAM2... and the default values as appropriate.

    Alternatively, maybe you shouldn't be using macros at all. Perhaps you could serve your purpose as well or better by writing an appropriate code generator. Or perhaps you would do well to use features of the C language proper (variables, functions, etc) instead of macros.