简体   繁体   中英

Two structs in different header files, both using the other

I've already gone through a bunch of threads on hear and a bunch of others I found on Google. I still can't seem to get this right.

//Room.h
#ifndef ROOM_H
#define ROOM_H

#include "Door.h"

typedef struct {
   Door* doors[3];

} Room;

#endif

//Door.h
#ifndef DOOR_H
#define DOOR_H

#include "Room.h"

typedef struct {
   Room* room1;
   Room* room2;
} Door;

//main.c
#include <stdio.h>
#include "Room.h"
int main() { ... }

I already tried adding this to the top of Door.h

typedef struct Room room1;
//typedef struct Room* room1;
//typedef stuct Room;
//typedef struct Room*;

All gave me this error:

"unknown type name 'Room'"

I want to keep these structs separate header files.

Try it like this:

typedef struct Room Room;
typedef struct Door Door;

struct Room{
   Door* doors[3];
};

struct Door{
   Room* room1;
   Room* room2;
};

The first two lines are the type declarations that will allow them to reference each other.

It won't matter how you separate these in the header files as long as the first two lines come first.


In your case, they can be split as follows:

room.h

typedef struct Door Door;

struct Room{
   Door* doors[3];
};

door.h

typedef struct Room Room;

struct Door{
   Room* room1;
   Room* room2;
};

C-way of struct reference:

room.h

typedef struct Room_s {
  struct Door_s * doors[3];
} Room_t;

door.h

typedef struct Door_s {
  struct Room_s *room1;
  struct Room_s *room2;
} Door_t;

Instead of creating anonymous structs and typedefing them, give the structs particular names as below:

common.h

typedef struct Door_ Door;
typedef struct Room_ Room;

room.h

#include "common.h"

struct Room_ {
  Door* doors[3];
};

door.h

#include "common.h"

struct Door_ {
  Room *room1;
  Room *room2;
};

Although, if you were planning to have room.h and door.h always used together, I'd just make one file to put all the definitions in.

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