如何将一个宏的结果传递给另一个宏? [英] How to pass a macro's result to another macro?

查看:294
本文介绍了如何将一个宏的结果传递给另一个宏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的C代码中有两个宏,可以帮助我编写某些变量的名称.例如,请考虑以下内容:

I have two macros in my C code the helps me to compose the name of certain variables. As an example, consider the following:

#define MACROA(name) A_##name
#define MACROB(name) B_##name

void *MACROB(MACROA(object));

因此,我正在尝试声明一个名为B_A_object的变量.但是,这不起作用,编译器向我抛出该消息:

So, I'm trying to declare a variable called B_A_object. However, this doesn't work and the compiler throws me the message:

object.c:27:21: error: a parameter list without types is only allowed in a function definition
void *MACROB(MACROA(object));
                    ^
object.c:26:26: note: expanded from macro 'MACROB'
#define MACROB(name) B_##name
                         ^

因此,似乎预处理器未采用MACROA(object)的结果,但它正在考虑表达式本身,以便尝试生成B_MACROA(object).那么,我该怎么做才能使预处理器考虑将宏的结果传递给另一个宏的方法?

So, it seems the preprocessor is not taking the result of MACROA(object), but it is considering the expression itself so that it tries to make B_MACROA(object). So, what do I have to do to make the preprocessor consider the result of a macro passed to another macro?

推荐答案

串联运算符的行为很奇怪.它先连接起来,然后再求值:

The concatenation operator acts weird. It concatenates first and evaluates later:

void *MACROB(MACROA(object));  // The original line
void *B_MACROA(object);       // Becomes this, nothing more to expand

您可以通过以下方式解决它:

You can solve it this way:

#define CONC(a,b) a ## b
#define MACROA(name) CONC(A_, name)
#define MACROB(name) CONC(B_, name)

这篇关于如何将一个宏的结果传递给另一个宏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆