I know how to have CMake output libs and bins depending on the build type (release, debug, etc), but, in order to reduce (re)compile times, I would like to have CMake build them in different subfolders.
Say I have this kind of tree
|- CMakeLists.txt
|- build/
|- src/
If I have debug, release, and relwithdebinfo builds, I want CMake to automatically create me a tree like
|- CMakeLists.txt
|- build/
|--- Debug/
|--- Release/
|--- RelWithDebInfo/
|- src/
and so on. Is this possible, if yes how can I achieve my goal ?
I do not want answers like "you should run CMake from different folders", since for visual studio this would lead to multiple solutions, etc. I want to be able to run CMake from only one folder, and have it handle subfolders by itself.
If you just leave CMake alone, it will do that automatically for generators that support multiple configurations (like Visual Studio).
If you override the default output locations, you should do so via the *_OUTPUT_DIRECTORY
target properties, which support generator expressions:
set_property(TARGET my_lib
PROPERTIES LIBRARY_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/$<CONFIG>/bin)
Note the $<CONFIG>
generator expression, which will expand to the name of the configuration (Debug, Release, etc.).
Note also that if you want the configuration directory to be at the bottom of the directory tree, you may not even have to give the generator expression explicitly:
This property specifies the directory into which library target files should be built. The property value may use generator expressions. Multi-configuration generators (VS, Xcode) append a per-configuration subdirectory to the specified directory unless a generator expression is used.
The three properties that control output directories are ARCHIVE_OUTPUT_DIRECTORY
, LIBRARY_OUTPUT_DIRECTORY
and RUNTIME_OUTPUT_DIRECTORY
. This page explains the difference.
In addition, you might want to also set the PDB_OUTPUT_DIRECTORY
for builds with pdb debug symbols.
Now, as mentioned in the beginning, all of this is only true for generators that support multiple configurations. For single-config generators like Makefiles, things are different. Here you have to settle for one specific configuration when running CMake (by setting the CMAKE_BUILD_TYPE
variable on the command line or the cmake-gui). If you want to switch configurations, you have to re-run CMake with a different setting for that variable.
These generators do not support having multiple configurations around at the same time. So if you use a single-config generator and you know that you need both debug and release builds regularly, it is best to keep separate build directories around for the different configurations and run cmake in each of them separately.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With