从include/linux/typecheck.h
中找到以下代码:
/*
* Check at compile time that something is of a particular type.
* Always evaluates to 1 so you may use it easily in comparisons.
*/
#define typecheck(type,x) \
({ type __dummy; \
typeof(x) __dummy2; \
(void)(&__dummy == &__dummy2); \
1; \\ <---- Why here is a 1;?
})
/*
* Check at compile time that 'function' is a certain type, or is a pointer
* to that type (needs to use typedef for the function type.)
*/
#define typecheck_fn(type,function) \
({ typeof(type) __tmp = function; \
(void)__tmp; \
})
1;
有什么区别吗?另外,块如何“计算为1”? 最佳答案
宏是一个语句表达式:https://gcc.gnu.org/onlinedocs/gcc/Statement-Exprs.html
最终表达式的值是宏“返回”的值。
如果typecheck
不属于x
,则type
宏会导致编译时警告。假设我声明了char *a
,然后尝试了typecheck(char, a)
,并使用gcc -Wall
编译:
1.c: In function 'main':
1.c:5:21: warning: comparison of distinct pointer types lacks a cast [enabled by default]
(void)(&__dummy == &__dummy2); \
^
1.c:14:2: note: in expansion of macro 'typecheck'
typecheck(char, a);
^
关于c - 了解Linux内核中的Typecheck,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35532224/