我在一个头文件中找到了我需要使用的设备的代码,虽然我已经做了多年的C,但我从来没有遇到过:
struct device {
};
struct spi_device {
struct device dev;
};
Run Code Online (Sandbox Code Playgroud)
它用作:
int spi_write_then_read(struct spi_device *spi,
const unsigned char *txbuf, unsigned n_tx,
unsigned char *rxbuf, unsigned n_rx);
Run Code Online (Sandbox Code Playgroud)
还在这里:
struct spi_device *spi = phy->spi;
Run Code Online (Sandbox Code Playgroud)
在哪里定义相同.
我不确定这个定义的重点是什么.它位于主板的Linux应用程序的头文件中,但它对它的使用感到困惑.任何解释,想法?之前见过这个的人(我相信你们有些人:).
谢谢!:BP:
oua*_*uah 42
这不是C,因为C结构必须包含至少一个命名成员:
(C11,6.7.2.1结构和联合说明符p8)"如果struct-declaration-list不包含任何命名成员,直接或通过匿名结构或匿名联合,则行为是未定义的."
但GNU C扩展:
GCC允许C结构没有成员:
Run Code Online (Sandbox Code Playgroud)struct empty { };结构的大小为零
https://gcc.gnu.org/onlinedocs/gcc/Empty-Structures.html
我不知道你的例子中这个构造的目的是什么,但总的来说我认为它可以用作结构类型的前向声明.请注意,在C++中,允许有一个没有成员的类.
在Linux 2.4中,spin_lock_t在Linux内核2.4(include/linux/spinlock.h)中的类型别名定义中有一个带有条件编译的空结构类型的示例:
#if (DEBUG_SPINLOCKS < 1)
/* ... */
typedef struct { } spinlock_t;
#elif (DEBUG_SPINLOCKS < 2)
/* ... */
typedef struct {
volatile unsigned long lock;
} spinlock_t;
#else /* (DEBUG_SPINLOCKS >= 2) */
/* ... */
typedef struct {
volatile unsigned long lock;
volatile unsigned int babble;
const char *module;
} spinlock_t;
#endif
Run Code Online (Sandbox Code Playgroud)
目的是节省一些空间而不必更改函数API以防万一DEBUG_SPINLOCKS < 1.它还允许定义类型的虚拟(零大小)对象spinlock_t.
另一个(最近的)Linux内核中的另一个例子是在include/linux/device.h中使用条件编译的空结构hack:
struct acpi_dev_node {
#ifdef CONFIG_ACPI
void *handle;
#endif
};
Run Code Online (Sandbox Code Playgroud)
有关最后一个示例,请参阅Greg Kroah-Hartman的讨论:
https://lkml.org/lkml/2012/11/19/453