C/C++ #define Macro inside macro?

前端 未结 4 1160
無奈伤痛
無奈伤痛 2021-01-18 13:04

I would like something like:

#define C_OR_CPP(C__, CPP__) #ifdef __cplusplus\\
CPP__\\
#else\\
C__\\
#endif

Is it possible? Maybe some dirt

4条回答
  •  无人共我
    2021-01-18 13:51

    My English is poor, and I'm sorry for language mistakes and typos if any.

    If #ifdef must not wrap the macro invocation, there is a solution not so graceful.

    g++ only: You may try this in selective occasions. But if there are commas in a or b, workarounds are still needed. It's simply based on the fact that __cplusplus is defined to "1" when in a C++ environment and remains itself while not.

    #define SELECT1(a, b) a
    #define SELECT__cplusplus(a, b) b
    #define xcat(a,b)  a##b
    #define concat(...) xcat(__VA_ARGS__)
    #define C_OR_CPP(C, CPP) concat(SELECT, __cplusplus)(C, CPP)
    
    C_OR_CPP(1, 2)
    

    Other Environments Check the __cplusplus macro, a compiler that comforming to standard C++ should generate

     #define __cplusplus value 
    

    and value should >= 199711L

提交回复
热议问题