C preprocessor Macro defining Macro

后端 未结 6 1175
耶瑟儿~
耶瑟儿~ 2020-12-29 01:49

Can you do something like this with a macro in C?

#define SUPERMACRO(X,Y) #define X Y

then

SUPERMACRO(A,B) expands to #define A B
<         


        
相关标签:
6条回答
  • 2020-12-29 01:53

    No. The order of operations is such that all preprocessor directives are recognized before any macro expansion is done; thus, if a macro expands into something that looks like a preprocessor directive, it won't be recognized as such, but will rather be interpreted as (erroneous) C source text.

    0 讨论(0)
  • 2020-12-29 01:54

    You cannot define macros in other macros, but you can call a macro from your macro, which can get you essentially the same results.

    #define B(x) do {printf("%d", (x)) }while(0)
    #define A(x) B(x)
    

    so, A(y) is expanded to do {printf("%d", (y)) }while(0)

    0 讨论(0)
  • 2020-12-29 01:54

    You might do this though: #define SUPERMACRO(X,Y) define X Y

    Then you can use your editors macro-expansion functionality and paste in the missing #.

    Or even better: Use a different, more powerful string-processing language as your preprocessor.

    0 讨论(0)
  • 2020-12-29 02:02

    Sorry, you cannot. You can call other macros in macros but not define new ones.

    0 讨论(0)
  • 2020-12-29 02:06

    Macros can't expand into preprocessing directives. From C99 6.10.3.4/3 "Rescanning and further replacement":

    The resulting completely macro-replaced preprocessing token sequence is not processed as a preprocessing directive even if it resembles one,

    0 讨论(0)
  • 2020-12-29 02:11

    You could try running it through with only the preprocess option, then compiling with the preprocessed file.

    0 讨论(0)
提交回复
热议问题