C Typedef – 不完整类型

所以,出乎意料的是,编译器决定吐面:“现场客户的类型不完整”。

这是代码的相关代码段:

customer.c

#include  #include  #include "customer.h" struct CustomerStruct; typedef struct CustomerStruct { char id[8]; char name[30]; char surname[30]; char address[100]; } Customer ; /* Functions that deal with this struct here */ 

customer.h

customer.h的头文件

 #include  #include  #ifndef CUSTOMER_H #define CUSTOMER_H typedef struct CustomerStruct Customer; /* Function prototypes here */ #endif 

这是我的问题所在:

customer_list.c

 #include  #include  #include "customer.h" #include "customer_list.h" #include "..\utils\utils.h" struct CustomerNodeStruct; typedef struct CustomerNodeStruct { Customer customer; /* Error Here*/ struct CustomerNodeStruct *next; }CustomerNode; struct CustomerListStruct; typedef struct CustomerListStruct { CustomerNode *first; CustomerNode *last; }CustomerList; /* Functions that deal with the CustomerList struct here */ 

这个源文件有一个头文件customer_list.h,但我认为它不相关。

我的问题

在customer_list.c中,在注释/* Error Here */ ,编译器抱怨field customer has incomplete type.

我整天都在谷歌上搜索这个问题,现在我正在拉出我的眼球并将它们与草莓混合。

这个错误的来源是什么?

提前致谢 :)

[PS,如果我忘记提及的话,请告诉我。 对你来说,这是一个充满压力的一天,你可能会告诉我们

将struct声明移动到标题:

 customer.h typedef struct CustomerStruct { ... } 

在C中,编译器需要能够计算出直接引用的任何对象的大小。 可以计算sizeof(CustomerNode)的唯一方法是,在构建customer_list.c时,编译器可以使用Customer的定义。

解决方案是将结构的定义从customer.ccustomer.h

您所拥有的是您尝试实例化的Customer结构的前向声明。 这不是真正允许的,因为编译器不知道结构布局,除非它看到它的定义。 因此,您需要做的是将源文件中的定义移动到标题中。

好像有点像

 typedef struct foo bar; 

没有标题中的定义将无法工作。 但有点像

 typedef struct foo *baz; 

只要您不需要在标题中使用baz->xxx ,它就会起作用。