C/C++ #define Macro inside macro?

白昼怎懂夜的黑 提交于 2020-01-11 08:36:09

问题


I would like something like:

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

Is it possible? Maybe some dirty hack with #include ?

Reason: I make a header where a struct uses a member variable of type vector<stuff>*, but in C i want it to simply be void*, you know.

TIA


回答1:


What's the problem with

#ifdef __cplusplus
#define C_OR_CPP(C, CPP) CPP
#else
#define C_OR_CPP(C, CPP) C
#endif

(Leaving names with double underscore to the implementation per phresnel remark)




回答2:


Not in C++. But you can

#ifdef __cplusplus
# define CPP
#else
# define C
#endif

I assume this is just a pathological example by you. Note also that double underscore is reserved to library implementors (see 17.6.4.3.2 Global names).

vector, but in C i want it to simply be void, you know.

So, what speaks against a solution like

struct Foo {
  #ifdef __cplusplus
  ...
  #else
  ...
  #endif
};

or what speaks against providing different APIs for different programming languages?




回答3:


AProgrammer already given you the right answer, but the answer to the "is it possible" part of the question is no. Macro expansion doesn't occur until after all preprocessor directives have been handled, so any macro that expands into a #define or #ifdef will be passed to the compiler as regular source text, which will cause the compiler to yak.




回答4:


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



来源:https://stackoverflow.com/questions/9431487/c-c-define-macro-inside-macro

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!