Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Single header file with all the necessary #include statements

I am currently working on program with a lot of source files. Sometimes it is difficult to keep track of what libraries I have already #included. Theoretically, I could make a single header file called Headers.h that just contains all the #include statements I need, then make all other header files #include "Headers.h".

Why is this a good/bad idea?

like image 460
abalabazn Avatar asked Dec 05 '14 04:12

abalabazn


3 Answers

Pros:

  • Slightly less maintenance as you don't have to keep track of which of your files are including headers from which libraries or other compoenents.

Cons:

  • Definitions in included files might conflict with each other. Especially in C where you don't have namespaces (you tagged with C and C++)
  • Macros in particular can cause hard to debug problems, where a macro definition unexpectedly conflicts with some name in your file or one of the other included files
  • Depending on which compiler you use, compilation times might blow out. If using a compiler that pre-compiles headers it might actually reduce compilation time, but if not the opposite will happen
  • You will often unnecessarily trigger rebuilds of files. If you have your build system set up correctly, then each source file will get rebuilt if any of the included files gets modified. If you always include all headers in your project, then a change to any of your headers will force recompilation of all your source files. Not likely to be an issue for system headers but it will be if you include your own headers in the master file as well.

On the whole I would not recommend that approach. The last con listed above it particularly important.

Best practice would be to include only headers that are needed for the code in each file.

like image 176
harmic Avatar answered Nov 12 '22 06:11

harmic


In complement of Harmic's answer, indeed the main issue is the build system (most builders work on file timestamp, not on file contents. omake is a notable exception).

Notice that if you only care about many dependencies, GNU make can be used with autodependencies, together with -M* options passed to GCC (i.e. to g++ and actually to the preprocessor).

However, many libraries are offering to their user a single header (e.g. <gtk/gtk.h>)

Also, a single header file is more friendly to precompiled headers technology. In particular, GCC wants a single header for precompilation.

See also ccache.

like image 42
Basile Starynkevitch Avatar answered Nov 12 '22 06:11

Basile Starynkevitch


Tracking all the required includes would be more difficult as they are abstracted from their c source files and not really supporting modularisation pus all the cons from #harmic

like image 22
crypticfool Avatar answered Nov 12 '22 07:11

crypticfool