linux 内核代码中的静态结构用于什么

What static struct in linux kernel code use for

您好,我正在按照Linux设备驱动程序开发一书编写Linux中的驱动程序。在如下示例代码中:

struct my_gpios {
    int reset_gpio;
    int led_gpio;
};
static struct my_gpiosneeded_gpios = {
    .reset_gpio = 47;
    .led_gpio = 41;
};

static struct resource needed_resources[] = {
    [0] = { /* The first memory region */
    .start = JZ4740_UDC_BASE_ADDR,
    .end = JZ4740_UDC_BASE_ADDR + 0x10000 - 1,
    .flags = IORESOURCE_MEM,
    .name = "mem1",
},
    [1] = {
    .start = JZ4740_UDC_BASE_ADDR2,Platform Device Drivers
    [ 126 ]
    .end = JZ4740_UDC_BASE_ADDR2 + 0x10000 -1,
    .flags = IORESOURCE_MEM,
    .name = "mem2",
},
};
static struct platform_devicemy_device = {
    .name = "my-platform-device",
    .id = 0,
    .dev = {
    .platform_data = &needed_gpios,
},
    .resource = needed_resources,
    .num_resources = ARRY_SIZE(needed_resources),
};
platform_device_register(&my_device);

我不明白语法 static struct_gpiosneeded_gpios = {} 的含义以及为什么 .reset_gpio 中有一个点。语法 static struct [] = {[0]={}, [1]={}} 的含义是什么?

你能给我一个参考 link 或关键词或关于 static struct {.a = VALUE, .b = VALUE,}; 的例子吗?

static struct something x = {
    .field_one = 123,
    .field_two = 456
};

这是一个 struct 初始化语法,来自 C99 (see here). This example creates a variable of type struct something named x, with fields field_one and field_two initialized to the specified values, and any other field initialized to 0. The static keyword is a storage duration specifier (see here) 的标准。


static struct something x[] = {[0]={ ... }, [1]={ ... }};

这是 struct 初始化和数组初始化语法的混合,也是 C99 (see here) 的标准。这个例子创建了一个 x 类型变量的数组 struct something,索引 0 处的那个用 {...} 初始化器的内容初始化,同样适用于那个在索引 1 处。由于最大的指定索引是 1,数组大小是 2.


I do not understand why they named the type is u32 or what is the purpose of __raw.

u32 类型只是 uint32_t 的简称。

我不确定您在何处看到 __raw,因为我似乎在内核源代码中找不到类似的东西。在任何情况下,Linux 内核作为一系列编译时注释用于具有不同用途的变量(__user__rcu 等)。这些不是 C 标准的一部分,通常甚至不是 GCC 扩展。它们主要是Sparse Linux 内核语义检查器

使用的提示。

Is there any standard or rule for naming the variable, macro, type,... in kernel?

有关详细信息,请参阅 Linux kernel coding style 文档页面。我建议您在尝试进行任何类型的内核编程之前阅读所有内容。您阅读的文档页数越多越好。

And what C standard i have to compliance when writing code in linux driver?

使用 C99 或更早版本的任何东西都可以。 Linux 内核代码不遵循单一的 C 标准,代码的各个部分甚至不符合标准,而是使用 GCC 扩展。有关详细信息,请参阅 here

你编译的时候一般不用选择标准,内核Makefile帮你做了,默认应该是C90。


无论如何,这些都是很多问题。如果你有一个具体的问题,我建议你单独提问,这样人们就能给你一个有针对性和更广泛的答案,因为问得太宽泛或太多都不是主题问题。