【发布时间】:2017-11-09 16:28:14
【问题描述】:
大家好,问题是我在这个宏中遇到了问题
#define ADD_COMP(s1,s2,type)({\
int _x=0;\
for(int i=0;i<n_addrs;i++){\
if(memcmp(s1,&(s2->##type),6)!=0){\
_x=-1;\
}else{\
break;\
}\
}\
_x;\
})
s1 是一个简单的数组,s2 是一个结构体,有 4 个向量作为成员,像这样
typedef struct example{
char[6] one,
char[6] two,
char[6] three
}example;
现在出于自己的原因,我需要创建一个函数,将大小为 6 字节的 s1 数组与仅示例的成员进行比较,因此为此我使用 ## 运算符编写了 ADD_CMP,以使其尽可能通用 所以我定义:
#define one
#define two
#define three
我以这种方式多次使用函数,希望宏扩展成功
ADD_COMP(some_array,example1,one)
ADD_COMP(some_array,example1,two)
ADD_COMP(some_array,example1,three)
但编译器返回错误:
error: pasting "->" and "one" does not give a valid preprocessing token
error: pasting "->" and "two" does not give a valid preprocessing token
error: pasting "->" and "three" does not give a valid preprocessing token
如何在不为每个结构成员编写相同函数的情况下修复它?
【问题讨论】:
-
编写一个函数并将该宏放入垃圾中。此外,您不需要按照错误提示将
type粘贴在->后面,只需写s2-> type -
确定一、二和三为空并不能说服我。如果删除这些定义会发生什么?另外,请发送minimal reproducible example。定义顺序等在这里是相关的。
-
char[6] one,应该是char one[6];。