【问题标题】:How to create a function-like macro token by pasting tokens together如何通过将标记粘贴在一起来创建类似函数的宏标记
【发布时间】:2019-12-05 01:40:51
【问题描述】:

我有一组预定义的宏(我无法更改),其中每个宏都将数组的索引作为输入。我想创建另一个宏,以便能够通过将标记粘贴在一起来选择要使用的先前定义的宏。

我已尝试创建一个包含 2 个参数的宏:x,它选择之前定义的要使用的宏,以及 ind,它被传递给选定的宏。

下面的代码是使用 https://www.onlinegdb.com/online_c_compiler 这样我就可以在将其放入一个相当大的应用程序之前弄清楚基本代码。

#include <stdio.h>

//struct creation
struct mystruct {
    int x;
    int y;
};

//create array of structs
struct mystruct sArr1[2] = {{1,2},{3,4}};
struct mystruct sArr2[2] = {{5,6},{7,8}};

//define macros
#define MAC1(ind) (sArr1[ind].x)
#define MAC2(ind) (sArr2[ind].y)

// Cannot change anything above this //

//my attempt at 2 input macro
#define MYARR(x,ind) MAC ## x ## (ind)

int main() {
    printf("%d\n", MYARR(1, 0));
    return 0;
}

我希望结果在索引0 处打印出sArr1x 值,即1。相反,我得到了这个输出

main.c:在函数“main”中: main.c:29:22:错误:粘贴“MAC1”和“(”未提供有效的预处理令牌 #define MYARR(x,ind) MAC ## x ## (ind) ^ main.c:33:19:注意:在宏“MYARR”的扩展中 printf("%d\n", MYARR(1, 0));

【问题讨论】:

  • 首先,令牌粘贴创建一个单个令牌。如果您仔细阅读错误消息,您会看到它正确地将MAC1 粘贴在一起,而问题是将MAC1((ind))粘贴在一起。你真的应该有一个single token(即一个预处理器符号)MAC1(吗?

标签: c macros c-preprocessor


【解决方案1】:

第 29 行应该是:

#define MYARR(x,ind) MAC##x(ind)

我测试过了。它打印了“1”,这就是你想要的。

【讨论】:

  • 但是请注意,MYARR 的所有实例中的第一个参数必须是显式常量 12,而不是具有此值的更复杂的表达式。
  • 非常简单的解决方案。我想我无法完全弄清楚。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-03-24
  • 2021-11-13
  • 1970-01-01
  • 2015-08-24
  • 1970-01-01
  • 2020-03-14
  • 1970-01-01
相关资源
最近更新 更多