在C中对宏参数进行类型检查 [英] Typechecking macro arguments in C
问题描述
是否可以对#define宏进行类型检查?例如:
Is it possible to typecheck arguments to a #define macro? For example:
typedef enum
{
REG16_A,
REG16_B,
REG16_C
}REG16;
#define read_16(reg16) read_register_16u(reg16); \
assert(typeof(reg16)==typeof(REG16));
上面的代码似乎无效.我在做什么错了?
The above code doesn't seem to work. What am I doing wrong?
顺便说一句,我正在使用gcc,并且我可以保证在此项目中将一直使用gcc.该代码不必具有可移植性.
BTW, I am using gcc, and I can guarantee that I will always be using gcc in this project. The code does not need to be portable.
推荐答案
gcc支持typeof
gcc supports typeof
例如来自Linux内核的typesafe min宏
e.g. a typesafe min macro taken from the linux kernel
#define min(x,y) ({ \
typeof(x) _x = (x); \
typeof(y) _y = (y); \
(void) (&_x == &_y); \
_x < _y ? _x : _y; })
但是它不允许您比较两种类型.请注意,尽管指针比较会产生警告-您可以像这样进行类型检查(也可以从linux内核中进行)
but it doesn't allow you to compare two types. Note though the pointer comparison which Will generate a warning - you can do a typecheck like this (also from the linux kernel)
#define typecheck(type,x) \
({ type __dummy; \
typeof(x) __dummy2; \
(void)(&__dummy == &__dummy2); \
1; \
})
大概您可以做类似的事情-即比较指向参数的指针.
Presumably you could do something similar - i.e. compare pointers to the arguments.
这篇关于在C中对宏参数进行类型检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!