typedef 结构的 C 前向声明

C forward declaration for typedef struct

我正在尝试转发声明 typedef struct wheels。

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; 
}

这给了我以下错误:

error: field ‘w’ has incomplete type wheels w;

error: field name not in record or union initializer .frontWheels = 2

error: field name not in record or union initializer .backWheels = 2

我知道我可以将整个 typedef struct wheels 移动到 typedef struct car 之上,它会起作用。

如何正确转发声明 struct wheels?

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

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

§6.2.5p1

At various points within a translation unit an object type may be incomplete (lacking sufficient information to determine the size of objects of that type) or complete (having sufficient information).

§6.7.2p3

A structure or union shall not contain a member with incomplete or function type (hence, a structure shall not contain an instance of itself, but may contain a pointer to an instance of itself), except that the last member of a structure with more than one named member may have incomplete array type; such a structure (and any union containing, possibly recursively, a member that is such a structure) shall not be a member of a structure or an element of an array.

第一个 typedef 声明了一个名为 wheels 的不完整类型。 car 结构使用该不完整类型作为成员。标准明确禁止这样做。

这就是第一条错误消息告诉您的内容。其他两个错误消息只是噪音。它们是编译器没有足够的信息来完成 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