在宏定义中使用多个宏 [英] Use multiple macros in a macro definition

查看:660
本文介绍了在宏定义中使用多个宏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在另一个宏的定义中使用多个宏,但是似乎无法将它们连接在一起。这是我要执行的操作的非常简化的版本:

I'm trying to use multiple macros in the definition of another macro, but seem to have problems concatenating them together. Here's a very simplified version of what I'm trying to do:

#include <stdio.h>

#define PICK_SET_A

#ifdef PICK_SET_A
#define SET A
#endif
#ifdef PICK_SET_B
#define SET B
#endif

#define ENABLE_VAR_1_A   1
#define ENABLE_VAR_2_A   1

#define ENABLE_VAR_1_B   0
#define ENABLE_VAR_2_B   0

#define MACRO_RESOLVE(var,set) ENABLE_VAR_##var##_##set

#define ENABLE_VAR_1     MACRO_RESOLVE(1, SET)
#define ENABLE_VAR_2     MACRO_RESOLVE(2, SET)

int main(int argc, char **argv) {

    fprintf(stdout, "VALUE: %d\n", ENABLE_VAR_1);

    return 0;
}

我希望结果为 0

但是,由于 MACRO_RESOLVE 宏无法解析,我遇到了编译错误我期望的方式:

However, I'm getting compile errors because the MACRO_RESOLVE macro isn't resolving the way I expect it to:

$ gcc -o asdf asdf.c
asdf.c:25:36: error: use of undeclared identifier 'ENABLE_VAR_1_SET'
    fprintf(stdout, "VALUE: %d\n", ENABLE_VAR_1);
                                   ^
asdf.c:20:26: note: expanded from macro 'ENABLE_VAR_1'
#define ENABLE_VAR_1     MACRO_RESOLVE(1, SET)
                         ^
asdf.c:18:32: note: expanded from macro 'MACRO_RESOLVE'
#define MACRO_RESOLVE(var,set) ENABLE_VAR_##var##_##set
                               ^
<scratch space>:229:1: note: expanded from here
ENABLE_VAR_1_SET
^
1 error generated.

所以看起来 SET 不是当我定义 ENABLE_VAR_1 时得到扩展。

So it looks like SET isn't getting expanded when I define ENABLE_VAR_1.

推荐答案

要构建宏名称,您需要在进行所有中间标记扩展的过程中进行足够的中间扩展。在在线观看

Since you are trying to build a macro name, you need to do enough intermediate expansions along the way for all tokens to expand. See it live here.

#include <stdio.h>

#define PICK_SET_A

#ifdef PICK_SET_A
#define SET A
#endif
#ifdef PICK_SET_B
#define SET B
#endif

#define ENABLE_VAR_1_A   1
#define ENABLE_VAR_2_A   1

#define ENABLE_VAR_1_B   0
#define ENABLE_VAR_2_B   0

#define MACRO_RESOLVE__(M) M
#define MACRO_RESOLVE_(V, S) MACRO_RESOLVE__(ENABLE_VAR_ ## V ##_## S)
#define MACRO_RESOLVE(var,set) MACRO_RESOLVE_(var, set)

#define ENABLE_VAR_1     MACRO_RESOLVE(1, SET)
#define ENABLE_VAR_2     MACRO_RESOLVE(2, SET)

int main(int argc, char **argv) {

    fprintf(stdout, "VALUE: %d\n", ENABLE_VAR_1);

    return 0;
}

这篇关于在宏定义中使用多个宏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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