Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 843
Cool Joe Avatar asked Jul 13 '12 03:07

Cool Joe


People also ask

Can you put a struct in a header file?

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.

Can header files include other header files?

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.

Can you have multiple header files?

Including Multiple Header Files:You can use various header files in a program.

Should structs be in header files C++?

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.


2 Answers

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;
};
like image 53
Mysticial Avatar answered Oct 19 '22 23:10

Mysticial


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;
like image 20
Dmitry Poroh Avatar answered Oct 20 '22 01:10

Dmitry Poroh