Reputation: 41
I'm working on a cpp project with many .cpp and .h files. I've been trying to improve its slow compile time, and found cpp files in project include many unnecessary headers that are actually not used in code.
Will this deteriorate cpp compile time?
I assume it could, but I want to know exactly why it affect cpp compile time, and theoretically how much it would.
Upvotes: 3
Views: 1069
Reputation: 305
#include
-ing unneeded libraries considerably slows compilation time.
You can get a sense of why this is true from a simple experiment. Compare the compile time of this code...
// no includes here!
int main() { return 0; }
...to this code (with several dozen #include
s I cut/pasted from a list I found)...
// <dozens of useless #includes here>
int main() { return 0; }
...and think about what happens when you compile them. I timed compilation of each and here's what I saw:
$$ time g++ no_includes.cpp -o no_includes
g++ no_includes.cpp -o no_includes 0.04s user 0.02s system 95% cpu 0.061 total
$$ time g++ all_the_includes.cpp -o all_the_includes
g++ all_the_includes.cpp -o all_the_includes 0.50s user 0.04s system 99% cpu 0.541 total
Half a second isn't very long to wait, but it's still 10 times longer than it needs to be. And in this rather contrived example, that extra time is mainly just the time the preprocessor needed to replace each #include
with a copy of the corresponding library. In a more realistic scenario, where the main()
in the second program actually made STL function calls, the compiler would need even more time to search through all the libraries for matching names, figure out which of those STL functions are viable candidates, and pick the best one.
Upvotes: 4