这个在大名鼎鼎的container_of就有出现,事实上一些面试题有时候也喜欢跟这个沾点边。
点击(此处)折叠或打开
- #define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
点击(此处)折叠或打开
- #define container_of(ptr, type, member) ({ \
- const typeof(((type *)0)->member)*__mptr = (ptr); \
- (type *)((char *)__mptr - offsetof(type, member)); })
点击(此处)折叠或打开
- struct test{
- int a;
- int b;
- };
- int main(void)
- {
- printf("offset_b = %ld\n", (size_t)(&((struct test*)0)->b));
- return 0;
- }
6. 宏参数的静态检查
下面的宏来自模块参数的定义部分:
点击(此处)折叠或打开
- #define __module_param_call(prefix, name, ops, arg, isbool, perm) \
- /* Default value instead of permissions? */ \
- static int __param_perm_check_##name __attribute__((unused)) = \
- BUILD_BUG_ON_ZERO((perm) < 0 || (perm) > 0777 || ((perm) & 2)) \
- + BUILD_BUG_ON_ZERO(sizeof(""prefix) > MAX_PARAM_PREFIX_LEN); \
- static const char __param_str_##name[] = prefix #name; \
- static struct kernel_param __moduleparam_const __param_##name \
- __used \
- __attribute__ ((unused,__section__ ("__param"),aligned(sizeof(void *)))) \
- = { __param_str_##name, ops, perm, isbool ? KPARAM_ISBOOL : 0, \
- { arg } }