I’m using cmake with C++ project. I want to use precompiled headers in GCC.
I want to run cmake once and then, when running make, I want this actions to happen:
- Run my custom tool (python script) on whole source tree. It generates precompiled.h headers in some subdirectories. It’s purpose is to scan *.h and *.cpp for #include’s and move them to common precompiled.h files.
- generate GCC’s precompiled headers (
g++ -c precompiled.h -o precompiled.h.gch) ONLY when precompiled.h file has changed after step 1. - build outdated targets (after step 2. because I want to use .gch file)
I’ve managed to add dependencies, so whenever I build any target, my python script’s target is executed (this is ugly, because now every target has to depend on single global_init target). Also I can modify my python script, so it doesn’t modify precompiled.h when it is not necessary.
But I don’t know what to do next. Is there any way to tell cmake that it should run my custom script and AFTER THAT determine if precompiled.h.gch must be created? Now it is always build (this file contains many #include’s, so it takes some time). Basically:
- Execute python script -> precompiled.h MAY BE updated
- Examine precompiled.h timestamp and if it’s newer -> build precompiled.h.gch
- Standard compilation steps
I’ve looked in many places, but cmake’s (and make’s) way of calculating dependencies seems too weak to accomplish this task.
In this question:
lazy c++
compilation always happens after lazycpp is executed. This would not be optimal in my case.
The following CMake commands may serve as a starting point for your project:
This command covers step 1. It invokes your python script which may update the existing
precompiled.hfiles inCMAKE_CURRENT_SOURCE_DIR.These commands cover step 2. The precompiled header is generated with a custom command which depends on
precompiled.hand implicitly on other headers thatprecompiled.hincludes.precompiled.h.gchis generated in theCMAKE_CURRENT_BINARY_DIRdirectory.Because the precompiled header generation requires
precompiled.hto be updated by the python script, we add a target level dependency on the targetscanner.These commands add standard compilation steps which generate an executable
main. The precompiled header is included as a default header with gcc’s-includeswitch. TheCMAKE_CURRENT_BINARY_DIRwhich containsprecompiled.h.gchis added as an include directory. gcc will pick upprecompiled.h.gchfrom there when precompiled.h is included (see Using Precompiled Headers).Finally the target dependency on
generate_precompiledensures that the precompiled header is updated if necessary.