Should I put the includes in the header file or the source file? If the header file contains the include statements, then if I include that header file in my source, then will my source file have all of the included files that were in my header? Or should I just include them in my source file only?
c') should include them itself, and not rely on its header to include them. The header should only include what users of the software need; not what the implementers need.
#include is a way of including a standard or user-defined file in the program and is mostly written at the beginning of any C/C++ program. This directive is read by the preprocessor and orders it to insert the content of a user-defined or system header file into the following program.
As a rule, put your includes in the . cpp files when you can, and only in the . h files when that is not possible. You can use forward declarations to remove the need to include headers from other headers in many cases: this can help reduce compilation time which can become a big issue as your project grows.
You make the declarations in a header file, then use the #include directive in every . cpp file or other header file that requires that declaration. The #include directive inserts a copy of the header file directly into the . cpp file prior to compilation.
Only put includes in a header if the header itself needs them.
Examples:
size_t
. Then #include <stddef.h>
in the header file.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With