我注意到,何时使用本机标量类型(整数、短整型、字符)或 stdint 提供的类型:uint32_t uint16_t uint8_t,似乎没有一致性或最佳实践。
这让我很烦恼,因为驱动程序是内核的重要组成部分,需要可维护、一致、稳定和良好。
这是 gcc 中的一个说明性示例(用于 raspberry pi 的业余项目):
// using native scalars
struct fbinfo {
unsigned width, height;
unsigned vwidth, vheight;
unsigned pitch, bits;
int x, y;
void *ptr;
unsigned size;
} __attribute__((aligned(16)));
// using stdint scalars
struct fbinfo {
uint32_t width, height;
uint32_t vwidth, vheight;
uint32_t pitch, bits;
int32_t x, y;
uint32_t ptr; // convert to void* in order to use it
uint32_t size;
} __attribute__((aligned(16)));
Run Code Online (Sandbox Code Playgroud)
对我来说,第一个例子似乎更合乎逻辑,因为这段代码只打算在树莓派上运行。在其他硬件上运行它是没有意义的。
第二个例子似乎更实用,因为它看起来更具描述性,因为 C 对整数的大小没有太多保证。它可能是 16 位或其他。uint32_t、uint_fast32_t 和变体保证精确或近似大小:例如至少或最多 X 字节。 …