tags:

views:

190

answers:

3

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!

+2  A: 

Include other includes in the header file if the contents of the header file uses types defined by such includes. (Sorry, that was a mouthful.)

In your case, math.h should definitely include struct.h, although, I argue that neither are good names for user-defined header files (the former because there is already a system-provided math.h; the latter because struct is a keyword). :-P

If your header file uses bool, then yes, it should include stdbool.h.

Chris Jester-Young
+3  A: 

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.h from math.h and forward declare box instead. Not that it makes a huge difference in this specific case.

Mark Byers
how would I go about making a forward declaration of bool?
overcyn
@overcyn: You can't: it's a macro not a type. You can't forward declare macros.
Mark Byers
C99 has a builtin type called `_Bool`. `stdbool.h` merely `typedef` s it to `bool`, and `#define` s `true` and `false`.
asveikau
+2  A: 

would "math.h" need to include "struct.h" as well?

No, because in math.h (not a great name, BTW) you are only dealing with pointers to a type. The definition is only needed if you are dealing with instances of a type. However, it would be good practice to include it, as the user who is going to traffic with actual instances will otherwise have to include it separately themselves.

anon
Uptick because of the final sentence. It's a prize pain in the neck to have to track down all the headers that some function needs, when the only header you should have to use is the one that declares it.
Liz Albin