I have 100 .h files in a externalFiles diretory. Around 10 .cpp files in my source includes these .h files.
So I removed all #include externalFiles/.*h
directives from my .cpp files and wrote them in a pch.h header that I include via Cmake's target_precompile_headers(${PROJECT_NAME} PRIVATE pch.h)
.
I checked my build times using precompiled headers via Cmake vs simply including pch.h in my .cpp files. I noted build times using:
set_property(GLOBAL PROPERTY RULE_LAUNCH_COMPILE "${CMAKE_COMMAND} -E time")
and
set_property(GLOBAL PROPERTY RULE_LAUNCH_LINK "${CMAKE_COMMAND} -E time")
Build time using precompiled headers
[1/2] Building CXX object CMakeFiles/AlgoCoding.dir/main.cpp.obj
Elapsed time: 11 s. (time), 11.413 s. (clock)
[2/2] Linking CXX executable AlgoCoding.exe
Elapsed time: 54 s. (time), 53.459 s. (clock)
Build time just including headers
[1/2] Building CXX object CMakeFiles/AlgoCoding.dir/main.cpp.obj
Elapsed time: 14 s. (time), 13.35 s. (clock)
[2/2] Linking CXX executable AlgoCoding.exe
Elapsed time: 28 s. (time), 28.109 s. (clock)
Conlusion
From these times it seems like using precompiled headers does reduce build time for the .obj creation of the .cpp file modified (main.cpp) but it increases the link time heavily.
Is this the case for everyone or am I doing something wrong here?
EDIT: 1
Experiment #2 to test Build times of precompiling headers.
I tried to include spdlog library(a header only library containing 100 .h files) into my bare-bones Cmake project (just a main.cpp logging 1 line into a file). Two methods of doing this.
- Just copy spdlog folder into my source and use #include directives in main.cpp
- Use precompiled headers (#include directive for spdlog in pch.h and pch.h added to project using
target_precompile_headers(${PROJECT_NAME} PRIVATE pch.h)
)
Build Time Results
----Method 1
[1/2] Building CXX object CMakeFiles/test.dir/main.cpp.obj
Elapsed time: 22 s. (time), 21.904 s. (clock)
[2/2] Linking CXX executable test.exe
Elapsed time: 18 s. (time), 18.311 s. (clock)
----Method 2
[1/2] Building CXX object CMakeFiles/test.dir/main.cpp.obj
Elapsed time: 18 s. (time), 18.231 s. (clock)
[2/2] Linking CXX executable test.exe
Elapsed time: 22 s. (time), 21.604 s. (clock)
Conclusion
Precompiling external headers in a barebones project still gives same total build time as just using #include directive. When using precompiled headers, the small time decrease in Building .obj file is compensated by increased time Linking CXX executable.
Is there something different I need to do to reduce build time when precompiling external .h files? Or is this the expected behaviour?