C向前声明typedef结构

时间:2018-12-29 19:16:25

标签: c struct typedef forward-declaration

我正在尝试转发声明typedef结构轮。

typedef struct wheels wheels;

typedef struct car {
  float topSpeed;
  wheels w;
} car;

typedef struct wheels {
  int frontWheels;
  int backWheels;
} wheels; 

int main() {
  car c = {
    .topSpeed = 255.0,
    .w = {
      .frontWheels = 2,
      .backWheels = 2,
    }
  };

  return 0; 
}

这给了我以下错误:

  

错误:“ w”字段的轮毂类型w不完整;

     

错误:字段名称不在记录或联合初始化程序中。frontWheels= 2

     

错误:字段名称不在记录或联合初始化程序中。backWheels= 2

我知道我可以将整个typedef struct车轮移到typedef struct车上方,并且它可以工作。

如何正确地向前声明结构轮?

2 个答案:

答案 0 :(得分:4)

以下是C标准的相关部分(加了强调):

§6.2.5p1

  

在翻译单元内的各个点上,对象类型可能是   不完整(缺少足够的信息来确定   该类型的对象)或完整的(具有足够的信息)。

§6.7.2p3

  

结构或联合体不得包含不完整的成员,或者   函数 type (因此,结构不得包含的实例   本身,但可能包含指向其实例的指针),但   具有一个以上命名成员的结构的最后一个成员   可能具有不完整的数组类型;这样的结构(以及任何联盟   包含(可能是递归的)具有这种结构的成员)   不得是结构的成员或数组的元素。

第一个typedef声明了一个不完整的类型,称为wheelscar结构使用该不完整类型作为成员。这是标准明确禁止的。

这就是第一条错误消息告诉您的内容。其他两个错误消息只是噪音。它们是由于编译器没有足够的信息来完成car结构的结果。

如另一个答案中所述,不完整类型的用途之一是声明指针。例如,链表中的一个节点,其中结构包含指向其自身的指针:

typedef struct node Node;   // struct node and Node are incomplete types here

struct node
{
    int value;
    Node *next;             // using an incomplete type to declare a pointer
};                          // struct node and Node are complete from here forward

答案 1 :(得分:2)

您只能拥有指向不完整的正向定义结构或联合的指针