Search code examples
cstructtypedefheading

C field has incomplete type


I have the folowing header file :

 #ifndef SERVER_STRUCTURES_H
 #define SERVER_STRUCTURES_H

typedef struct game {
  int id;
  struct player player1;
  struct player player2;
  struct game *next;
} game_t;

typedef struct player {
  int id;
  int score;
  struct player *player1;
  struct game *g ;
} player_t;

#endif

I get the error: field 'player1' has incomplete type struct player player1

and

field 'player2' has incomplete type struct player player2.

What is the mistake? thank you!


Solution

  • Declarations must be before where they are used, so the two declarations should be swapped. To allocate player1 and player2, the compiler will require the full declaration of struct player.

    Then, you should tell the compiler that struct game will be declared later. It is enough information to create "pointer to something".

    #ifndef SERVER_STRUCTURES_H
    #define SERVER_STRUCTURES_H
    
    struct game;
    
    typedef struct player {
      int id;
      int score;
      struct player *player1;
      struct game *g ;
    } player_t;
    
    typedef struct game {
      int id;
      struct player player1;
      struct player player2;
      struct game *next;
    } game_t;
    
    #endif