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

后端 未结 7 1301
醉话见心
醉话见心 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:19

    There's no easy way to do this. The closest you can come is to #define a large number of IFDEF macros such as:

    #undef IFDEF_INT_MAX
    #ifdef INT_MAX
    #define IFDEF_INT_MAX(X)  X
    #else
    #define IFDEF_INT_MAX(X)
    #endif
    
    #undef IFDEF_BLAH_MAX
    #ifdef BLAH_MAX
    #define IFDEF_BLAH_MAX(X)  X
    #else
    #define IFDEF_BLAH_MAX(X)
    #endif
    
         :
    

    since you need a lot of them (and they might be useful multiple places), it makes a lot of sense to stick all these in their own header file 'ifdefs.h' which you can include whenever you need them. You can even write a script that regenerates ifdef.h from a list of 'macros of interest'

    Then, your code becomes

    #include "ifdefs.h"
    #define print_max(TYPE) \
    IFDEF_##TYPE##_MAX( printf("%lld\n", TYPE##_MAX); )
    
    print_max(INT);
    print_max(BLAH);
    

提交回复
热议问题