How to structure #includes in C

You should include foo.h inside foo.c. This way other c files that include foo.h won't carry bar.h unnecessarily. This is my advice for including header files:

  • Add include definitions in the c files - this way the file dependencies are more obvious when reading the code.
  • Split the foo.h in two separate files, say foo_int.h and foo.h. The first one carries the type and forward declarations needed only by foo.c. The foo.h includes the functions and types needed by external modules. This is something like the private and public section of foo.
  • Avoid cross references, i.e. foo references bar and bar references foo. This may cause linking problems and is also a sign of bad design

As others have noted, a header foo.h should declare the information necessary to be able to use the facilities provided by a source file foo.c. This would include the types, enumerations and functions provided by foo.c. (You don't use global variables, do you? If you do, then those are declared in foo.h too.)

The header foo.h should be self-contained and idempotent. Self-contained means that any user can include foo.h and not need to worry about which other headers may be needed (because foo.h includes those headers). Idempotent means that if the header is included more than once, there is no damage done. That is achieved by the classic technique:

 #ifndef FOO_H_INCLUDED
 #define FOO_H_INCLUDED
 ...rest of the contents of foo.h...
 #endif /* FOO_H_INCLUDED */

The question asked:

File foo.c includes foo.h, which contains all declarations for foo.c; same for bar.c and bar.h. Function foo1() inside foo.c calls bar1(), which is declared in bar.h and defined in bar.c. Now the question is, should I include bar.h inside foo.h, or inside foo.c?

It will depend on whether the services provided by foo.h depend on bar.h or not. If other files using foo.h will need one of the types or enumerations defined by bar.h in order to use the functionality of foo.h, then foo.h should ensure that bar.h is included (by including it). However, if the services of bar.h are only used in foo.c and are not needed by those who use foo.h, then foo.h should not include bar.h


I would only include header files in a *.h file that required for the header file itself. Header files that are needed for a source file, in my opinion, should be included in the source file so that the dependencies are obvious from the source. Header files should be be built to handle multiple inclusion so you could put it in both if required for clarity.

Tags:

C

Header

Include