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.
If a struct is declared in a header file in C++, you must include the header file everywhere a struct is used and where struct member functions are defined. The C++ compiler will give an error message if you try to call a regular function, or call or define a member function, without declaring it first.
The answer is that yes, it can; header files (that is, #include directives) may be nested. (They may be nested up to a depth of at least 8, although many compilers probably allow more.) Once funcs. h takes care of its own needs, by including <stdio.
Including Multiple Header Files:You can use various header files in a program.
In a lot of cases, the struct is particular to a project and it is fine to include it in the header file with all the function prototypes and global constants.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With