【问题标题】:Understanding typecheck in linux kernel了解 linux 内核中的类型检查
【发布时间】:2016-02-21 04:12:23
【问题描述】:

以下代码来源于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”?

【问题讨论】:

    标签: c linux-kernel macros


    【解决方案1】:

    宏是一个语句表达式:https://gcc.gnu.org/onlinedocs/gcc/Statement-Exprs.html

    最终表达式的值是宏“返回”的值。

    如果x 不属于typetypecheck 宏会导致编译时警告。假设我声明了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);
      ^
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-05
      • 1970-01-01
      • 2011-12-04
      • 1970-01-01
      • 2013-03-24
      • 2014-02-05
      • 2013-10-20
      • 1970-01-01
      相关资源
      最近更新 更多