宏依赖宏 [英] macro dependent macro
问题描述
是否有可能做这样的事情:
#define F(x)\
#ifdef DOUBLE \
2 * x \
#else \
x \
#endif
,这样当我使用 F
时,它的扩展取决于宏 DOUBLE
是否定义?我不这么认为,但我很有希望。 GNU扩展很好。
编辑
为了回应一些答案,我真的使用它来做一些代码代,代码根据定义的位置略有不同。由于包含某些文件的顺序以及需要定义相关宏的位置,因此要切换它需要一些分解。我可能不得不这样做,但如果我不必从这个角落解开我自己就会感到兴奋!
我们可以限制问题,你可以做到这一点。具体而言,如果您可以保证 那么你可以使用间接方式和令牌串联: 使用范例: 预处理结果: 如果 Is it possible to do something like this: so that when I use Edit
In response to some of the answers, I'm really using this to do some code generation, where the code is slightly different depending on where it gets defined. Because of the order in which some files are included and where the relevant macros need to be defined, switching it around that way requires a bit of factoring. I may have to do it, but would be thrilled if I don't have to unpaint myself from this corner! If we can constrain the problem, you can accomplish this. Specifically, if you can guarantee that then you can use an indirect approach with token concatenation: Usage example: Result after preprocessing: This approach will also work if 这篇关于宏依赖宏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! DOUBLE
或者
#define DOUBLE
),
#define F_IMPL_(x)DOUBLE_IS_DEFINED
#define F_IMPL_DOUBLE(x)DOUBLE_NOT_DEFINED
#define F_1(x,m)F_2(x,m)
#define F_2 (x,m)F_IMPL_ ## m(x)
#define F(x)F_1(x,DOUBLE)
pre $ F $
#define DOUBLE
F(t)
DOUBLE_NOT_DEFINED
DOUBLE_IS_DEFINED
DOUBLE
(如果定义的话)定义为一个扩展为单个已知标记的宏,如果该标记可以形成标识符的一部分(例如, TRUE
或 1
)。要处理这个问题,你只需将 F_IMPL _
宏重命名为 F_IMPL_ {TOKEN}
(例如 F_IMPL_TRUE
或 F_IMPL_1
)。 #define F(x) \
#ifdef DOUBLE \
2*x \
#else \
x \
#endif
F
, what it expands to depends on whether the macro DOUBLE
is defined? I don't think so, but I'm hopeful. GNU expansions are fine.DOUBLE
is either
#define DOUBLE
),#define F_IMPL_(x) DOUBLE_IS_DEFINED
#define F_IMPL_DOUBLE(x) DOUBLE_NOT_DEFINED
#define F_1(x, m) F_2(x, m)
#define F_2(x, m) F_IMPL_ ## m ( x )
#define F(x) F_1(x, DOUBLE)
F(t)
#define DOUBLE
F(t)
DOUBLE_NOT_DEFINED
DOUBLE_IS_DEFINED
DOUBLE
(if it is defined) is defined as a macro that expands to a single known token, if that token can form part of an identifier (e.g., TRUE
or 1
). To handle this, you just have to rename the F_IMPL_
macro to F_IMPL_{TOKEN}
(e.g., F_IMPL_TRUE
or F_IMPL_1
).