简体   繁体   English

两个结构在不同的头文件中,都使用另一个

[英]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. 我已经在听过一堆线索,还有一些我在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 我已经尝试将其添加到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 room.h

typedef struct Door Door;

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

door.h door.h

typedef struct Room Room;

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

C-way of struct reference: 结构参考的C-way方式:

room.h room.h

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

door.h 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 COMMON.H

typedef struct Door_ Door;
typedef struct Room_ Room;

room.h room.h

#include "common.h"

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

door.h 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. 虽然,如果你计划将room.hdoor.h一起使用,我只需要制作一个文件来放入所有的定义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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