简体   繁体   English

C / C ++ #define宏内宏?

[英]C/C++ #define Macro inside macro?

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 ? 也许#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. 原因:我创建了一个头部,其中一个结构使用了一个类型为vector<stuff>*的成员变量,但是在C中我希望​​它只是void* ,你知道。

TIA TIA

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) (将双下划线的名称留给每个菲涅耳评论的实现)

Not in C++. 不是在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). 另请注意,双重下划线保留给库实现者(请参见17.6.4.3.2全局名称)。

vector , but in C i want it to simply be void , you know. 矢量,但在C中我希望​​它只是无效 ,你知道。

So, what speaks against a solution like 那么,什么反对像这样的解决方案

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

or what speaks against providing different APIs for different programming languages? 或者反对为不同的编程语言提供不同的API?

AProgrammer already given you the right answer, but the answer to the "is it possible" part of the question is no. AProgrammer已经给你正确的答案,但问题的“可能”部分的答案是否定的。 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. 在处理完所有预处理程序指令之后才会发生宏扩展,因此任何扩展为#define#ifdef宏都将作为常规源文本传递给编译器,这将导致编译器牦牛。

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. 如果#ifdef不能包装宏调用,那么解决方案就不那么优雅了。

g++ only: You may try this in selective occasions. 仅限g ++:你可以在选择性场合尝试这个。 But if there are commas in a or b, workarounds are still needed. 但是如果a或b中有逗号,则仍需要解决方法。 It's simply based on the fact that __cplusplus is defined to "1" when in a C++ environment and remains itself while not. 它只是基于这样一个事实:__ cplusplus在C ++环境中定义为“1”,而在没有的情况下保持自身。

#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 其他环境检查__cplusplus宏,这是一个符合标准C ++的编译器应该生成的

 #define __cplusplus value 

and value should >= 199711L 和值应> = 199711L

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM