The problem with the structures, where to put them and how to refer to them in the headers?

Well, now I have a dilemma, and neither my knowledge of C (which is not the biggest), nor the omnipotent Google, seem to be able to help me:

I have some structures for the prototype of the game:

  • Map (Uhm ... Map ..)
  • Chara (base for enemy players)
  • Player (player)

Now the problem is this: you Mapneed a link to Player, which is built on it Player, giving it Mapand Chara, but also Chararequired Map.

If I declare structures in the header files and end them with #ifndef, I start the loop cycle when I include headers from other headers.

When I declare structures in .c files, I use extern struct Map mapetc., but then I run into a problem like invalid use of incomplete declarationor forward declaration of struct XXX.

It's 4 a.m. here, and I would like to spend more time rewriting the engine (which already exists in both Python and JavaScript ... yes, I have too much time!) And then trying every possible combination of search terms for the rest parts of the night.

I know this can be REALLY easy, but here it is 30 ° C, so please have mercy with my skills "^"

EDIT
Because my problem used the typedefs and caf answers, they did not include them, I had to play a little with it to make it all work. Therefore, to help people who can find this answer through SE, I will add the following code:

map.h

typedef struct _Player Player;

typedef struct _Map {
    ...
    Player *player;
    ...
} Map;

map.c

// include both player.h and chara.h

player.h

typedef struct _Map Map;
typedef struct _Chara Chara;

typedef struct _Player {
    Chara *chara;
    ...
} Player;

Player *player_create(Map *map, int x, int y);

player.c

// include player.h, chara.h and map.h
+3
2

, :

Map.h

#ifndef _MAP_H
#define _MAP_H

struct player;

struct map {
    struct player *player;
    ...
};

#endif /* _MAP_H */

chara.h

#ifndef _CHARA_H
#define _CHARA_H

struct map;

struct chara {
    struct map *map;
    ...
};

#endif /* _CHARA_H */

player.h

#ifndef _PLAYER_H
#define _PLAYER_H

struct map;
struct chara;

struct player {
    struct map *map;
    struct chara *chara;
    ...
};

#endif /* _PLAYER_H */

( ), #include . , map :

Map.h

#ifndef _MAP_H
#define _MAP_H

#include "player.h"

struct map {
    struct player p[10];
    ...
};

#endif /* _MAP_H */

. map.h player.h, player.h map.h - .

+3

, , , - .

0

Source: https://habr.com/ru/post/1752567/


All Articles