Suppose I define a struct in “struct.h” like so
struct box {
int value;
}
and I use that struct in another file say “math.c”
#include "struct.h"
struct box *sum(struct box *a1, struct box *a2) {
struct box *a3 = malloc(sizeof (struct box));
a3->value = a1->value + a2->value;
return a3;
}
would “math.h” need to include “struct.h” as well?
#include "struct.h"
struct box *sum(struct box *a1, struct box *a2);
And what if struct box were replaced with bool, do I need to include stdbool.h in both the header and c file? it seems like the compiler wants this.
When should you include files in the header rather than the .c? also wondering if theres something unusual with my example.
Thanks!
The general rule is to include as little as possible in your header files.
Use forward declarations instead of definitions where possible, then you can move the definitions to the .c file. This can reduce the number of files you need to include in your header files.
In your specific example you could remove the include of
struct.hfrommath.hand forward declare box instead. Not that it makes a huge difference in this specific case.