Is it possible for C preprocessor macros to contain preprocessor directives?

后端 未结 7 1296
醉话见心
醉话见心 2020-12-08 19:33

I would like to do the equivalent of the following:

#define print_max(TYPE) \\
#  ifdef TYPE##_MAX \\
     printf(\"%lld\\n\", TYPE##_MAX); \\
#  endif

prin         


        
7条回答
  •  难免孤独
    2020-12-08 20:25

    The Boost Preprocessor (which works for C as well as C++, even though Boost as a whole is a C++ library) library can help with this kind of task. Instead of using an #ifdef within a macro (which isn't permitted), it helps you include a file multiple times, with different macros defined each time, so that the file can use #ifdef.

    The following code, if saved to max.c, should do what you want for each of the words listed in the MAXES #define at the top of the file. However, it won't work if any of the _MAX values are floating point, since the preprocessor can't handle floating point.

    (Boost Processor is a handy tool, but it's not exactly straightforward; you can decide whether or not this approach is an improvement over copy-and-paste.)

    #define MAXES (SHRT)(INT)(LONG)(PATH)(DOESNT_EXIST)
    
    #if !BOOST_PP_IS_ITERATING
    
    /* This portion of the file (from here to #else) is the "main" file */
    
    #include 
    #include 
    #include 
    
    /* Define a function print_maxes that iterates over the bottom portion of this
     * file for each word in MAXES */
    #define BOOST_PP_FILENAME_1 "max.c"
    #define BOOST_PP_ITERATION_LIMITS (0,BOOST_PP_DEC(BOOST_PP_SEQ_SIZE(MAXES)))
    void print_maxes(void) {
    #include BOOST_PP_ITERATE()
    }
    
    int main(int argc, char *argv[])
    {
        print_maxes();
    }
    
    #else
    
    /* This portion of the file is evaluated multiple times, with
     * BOOST_PP_ITERATION() resolving to a different number every time */
    
    /* Use BOOST_PP_ITERATION() to look up the current word in MAXES */
    #define CURRENT BOOST_PP_SEQ_ELEM(BOOST_PP_ITERATION(), MAXES)
    #define CURRENT_MAX BOOST_PP_CAT(CURRENT, _MAX)
    
    #if CURRENT_MAX
    printf("The max of " BOOST_PP_STRINGIZE(CURRENT) " is %lld\n", (long long) CURRENT_MAX);
    #else
    printf("The max of " BOOST_PP_STRINGIZE(CURRENT) " is undefined\n");
    #endif
    
    #undef CURRENT
    #undef CURRENT_MAX
    
    #endif
    

提交回复
热议问题