I have a situation where two of my header files require the data structures defined in either one, i.e. no matter which order you include them it won’t compile
however, one of the problem data structures only contains pointers to the data structure declared in the other header file so I would have though that technically it doesn’t need to know at this point how big the data structure is so it shouldn’t be complaining
A simplified example of what I mean is outlined below. I would have thought that the array of modes in Library doesn’t need to know how big a Mode is, only how big a pointer to a Mode is therefore the compiler shouldn’t complain if it hasn’t yet seen the declaration of Mode in the other header file.
header_1.h
typedef struct
{
Mode **modes;
} Library;
header_2.h
typedef struct
{
int number;
char *name;
} Mode;
As currently written, your example does not show the mutual cross-referencing that you mention in the question.
The compiler must be told something about each type it uses. You could use in
header_1.hjust:That would make it compile, at least. The compiler doesn’t need the details, but it does need to know that
Modesis a type.Edit:
Note that
header_2.hshould be modified for this to work. You have to ensure that eachtypedefappears just once. After you have the typedefs in place, you specify the structure content (definition) once, and you omit the keywordtypedefand the typedef name from the structure definition. And you have to decide on exactly the cross-references will be managed. For example, shouldheader_1.hincludeheader_2.hanyway.I don’t remember encountering a case where I really needed mutually referencing structures (in quite a long time programming — long enough that I could have forgotten a example).I do now remember a case of structures mutually referencing each other; it was in a version ofmakeoriginally written for Minix. I still regard such a requirement as somewhat ‘pathological’ (or, if you prefer, as a ‘code smell’) and as something to be avoided whenever possible. If you really must manage it, then the section below explains how I’d go about doing it (and more or less how themakeprogram did go about it).Mutually-referencing structures
If you truly have two mutually referencing structures, you should (re)consider why you think two headers are better than one. If you still need two headers, you use an idiom like:
header_1.h
header_2.h
The repeated
typedef‘detection’ code is not nice; a single header is better, in my estimation. However, you can includeheader_1.handheader_2.habove in either order and it should compile.