Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will there be a performance hit on including unused header files in C/C++?

I have a project where each C/C++ file uses a bunch of header files. But about 70-80% of the header files that each C/C++ file uses is the same. So to make my code more readable, I am planning to include all the headers that I will need in the project into a single header file say common_headers.h and include this in all my C/C++ files like this:

#include "common_headers.h"

Now this will include all the necessary headers but also few extra headers that will not be used by an individual file. I want to know if doing this way, would it hit the performance at run time by any chance?

I am fine with a few milliseconds extra delay for compiling the code, but I want to know if this will impact my runtime performance?

Description of headers used:

  1. Most of them are standard C/C++ headers.
  2. The user defined headers have inline template functions in them .
  3. No static functions in user defined headers.

This is my Compiler: g++ (GCC) 4.4.7 20120313 (Red Hat 4.4.7-3)

like image 224
Vivek V K Avatar asked Jul 29 '14 05:07

Vivek V K


1 Answers

COMPILATION:

If something is included then it has to analyzed even if it will never be actually compiled and linked, so compilation time will increase for sure - Do not include unused headers.

RUNTIME:

It has been already mentioned by @DonReba that unused headers may include some pragma directives that can change the resulting executable, but usually it won't be the case.

Most of the unused functions and declaraions will be optimized out, excluding some specific cases - Do unused functions get optimized out?. The resulting exe may become a bit bigger, but those functions and variables won't be used, so overall impact will be minimal. - - Nonetheless, do not include unused headers.

SUMMARY:

If you can modify your source code to not include anything unneeded - modify it.

Personnaly I prefer to have self-contained modules(headers), that include everything they need - nothing more, nothing less. Such modules can be added and removed without hindsight and possibility that some unneeded dependency has been left. They are still not panacea, but coupled with attentiveness and some code analysis they will keep your program free from deadweight headers.

EDIT:

Precompiled headers:

Precompiled headers are used to reduce compilation time for often used, but rarely changed headers(system headers, huge project headers), so if those unused headers are included in the precompiled header, then the compilation time effect during subsequent compilations will be minimized. Still, all runtime issues, no matter how small they are, stay the same as for simple header includes.

like image 58
Eugene Podskal Avatar answered Oct 12 '22 22:10

Eugene Podskal