简体   繁体   中英

C forward declaration for typedef struct

I'm trying to forward declare 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; 
}

This gives me the following errors:

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

I know I can move the entire typedef struct wheels above the typedef struct car and it would work.

How do I forward declare struct wheels correctly?

Here are the relevant sections from the C standard (emphasis added):

§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.

The first typedef declares an incomplete type called wheels . The car structure uses that incomplete type as a member. That's explicitly forbidden by the standard.

That's what the first error message is telling you. The other two error messages are just noise. They are the result of the fact that the compiler did not have sufficient information to complete the car structure.

As mentioned in the other answer, one of the uses of incomplete types is to declare pointers. For example, a node in a linked list where the structure contains a pointer to itself:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM