C++ – Debug vs Release in CMake


In a GCC compiled project,

  • How do I run CMake for each target type (debug/release)?
  • How do I specify debug and release C/C++ flags using CMake?
  • How do I express that the main executable will be compiled with g++ and one nested library with gcc?

Best Solution

With CMake, it's generally recommended to do an "out of source" build. Create your CMakeLists.txt in the root of your project. Then from the root of your project:

mkdir Release
cd Release
cmake -DCMAKE_BUILD_TYPE=Release ..

And for Debug (again from the root of your project):

mkdir Debug
cd Debug
cmake -DCMAKE_BUILD_TYPE=Debug ..

Release / Debug will add the appropriate flags for your compiler. There are also RelWithDebInfo and MinSizeRel build configurations.

You can modify/add to the flags by specifying a toolchain file in which you can add CMAKE_<LANG>_FLAGS_<CONFIG>_INIT variables, e.g.:


See CMAKE_BUILD_TYPE for more details.

As for your third question, I'm not sure what you are asking exactly. CMake should automatically detect and use the compiler appropriate for your different source files.