How to evaluate a nested preprocessor macro

前端 未结 1 395
孤城傲影
孤城傲影 2021-01-12 18:13

let\'s say I want to select the behaviour of a certain preprocessor directive evaluating at compile time the concatenation of a constant string and the result of another mac

相关标签:
1条回答
  • 2021-01-12 18:47

    It's possible, you just need to add some extra layers of macros. The key is that when you use the token-pasting operator ##, the preprocessor will not expand its operands. But, if you add another layer of macros, the preprocessor will expand those arguments. For example:

    #define CASE1 text1
    #define CASE2 text2
    #define CASE3 text3
    #define SCENARIO 3
    
    #define TOKENPASTE_HELPER(x, y) x ## y
    #define TOKENPASTE(x, y) TOKENPASTE_HELPER(x, y)
    #define FUNCTION TOKENPASTE(CASE, SCENARIO)
    

    When the preprocessor expands FUNCTION, it expands TOKENPASTE. When it expands TOKENPASTE, it expands its arugments (so SCENARIO gets replaced by 3), since neither of its arguments are operands of the token-pasting operator. Next, it expands TOKENPASTE_HELPER, which does the actual token pasting to make CASE3. Finally, it expands the CASE3 macro to get text3.

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