Linux 内核对 C 采取的 typedef 策略是最好的。本质上,策略是不使用 typedef,除非您正在创建新的类型抽象。这在架构之间的低级类型不同但内核用户想要一个通用类型的情况下很有用。例如 u64 被赋予特定类型,但底层类型可能会在构建或架构之间发生变化。
Chapter 5: Typedefs
请不要使用“vps_t”之类的东西。
使用 typedef 是一个错误
结构和指针。当你看到
一个
vps_t a;
在源码中是什么意思?
相反,如果它说
struct virtual_container *a;
您实际上可以分辨出“a”是什么。
很多人认为 typedef
“帮助可读性”。不是这样。他们是
仅适用于:
(a) 完全不透明的物体(其中
typedef 被积极地用于隐藏
对象是什么)。
Example: "pte_t" etc. opaque objects that you can only access using
the proper accessor functions.
NOTE! Opaqueness and "accessor functions" are not good in themselves.
The reason we have them for things like pte_t etc. is that there
really is absolutely _zero_ portably accessible information there.
(b) 清除整数类型,其中
抽象帮助避免混淆
无论是“int”还是“long”。
u8/u16/u32 are perfectly fine typedefs, although they fit into
category (d) better than here.
NOTE! Again - there needs to be a _reason_ for this. If something is
"unsigned long", then there's no reason to do
typedef unsigned long myflags_t;
but if there is a clear reason for why it under certain circumstances
might be an "unsigned int" and under other configurations might be
"unsigned long", then by all means go ahead and use a typedef.
(c) 当你从字面上使用稀疏
创建一个 new 类型
类型检查。
(d) 与
标准 C99 类型,在某些
特殊情况。
Although it would only take a short amount of time for the eyes and
brain to become accustomed to the standard types like 'uint32_t',
some people object to their use anyway.
Therefore, the Linux-specific 'u8/u16/u32/u64' types and their
signed equivalents which are identical to standard types are
permitted -- although they are not mandatory in new code of your
own.
When editing existing code which already uses one or the other set
of types, you should conform to the existing choices in that code.
(e) 可以在用户空间中安全使用的类型。
In certain structures which are visible to userspace, we cannot
require C99 types and cannot use the 'u32' form above. Thus, we
use __u32 and similar types in all structures which are shared
with userspace.
也许还有其他情况,但是
规则基本上应该是从不
除非可以,否则永远使用 typedef
明显符合这些规则之一。
一般来说,指针或结构
具有合理的元素
应该从不直接访问
类型定义。