Where to put include statements, header or source? Where to put include statements, header or source? c c

Where to put include statements, header or source?


Only put includes in a header if the header itself needs them.

Examples:

  • Your function returns type size_t. Then #include <stddef.h> in the header file.
  • Your function uses strlen. Then #include <string.h> in the source file.


There's been quite a bit of disagreement about this over the years. At one time, it was traditional that a header only declare what was in whatever module it was related to, so many headers had specific requirements that you #include a certain set of headers (in a specific order). Some extremely traditional C programmers still follow this model (religiously, in at least some cases).

More recently, there's a movement toward making most headers standalone. If that header requires something else, the header itself handles that, ensuring that whatever it needs is included (in the correct order, if there are ordering issues). Personally, I prefer this -- especially when the order of headers can be important, it solves the problem once, instead of requiring everybody who uses it to solve the problem yet again.

Note that most headers should only contain declarations. This means adding an unnecessary header shouldn't (normally) have any effect on your final executable. The worst that happens is that it slows compilation a bit.


Your #includes should be of header files, and each file (source or header) should #include the header files it needs. Header files should #include the minimum header files necessary, and source files should also, though it's not as important for source files.

The source file will have the headers it #includes, and the headers they #include, and so on up to the maximum nesting depth. This is why you don't want superfluous #includes in header files: they can cause a source file to include a lot of header files it may not need, slowing compilation.

This means that it's entirely possible that header files might be included twice, and that can be a problem. The traditional method is to put "include guards" in header files, such as this for file foo.h:

#ifndef INCLUDE_FOO_H#define INCLUDE_FOO_H/* everything in header goes here */#endif