overcyn
overcyn

Reputation: 33

what files need to be include in header files? structs? <stdbool.h>?

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!

Upvotes: 3

Views: 1598

Answers (3)

Mark Byers
Mark Byers

Reputation: 838276

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.

Upvotes: 4

anon
anon

Reputation:

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.

Upvotes: 3

C. K. Young
C. K. Young

Reputation: 223023

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.

Upvotes: 2

Related Questions