CMake and the Default Build Type

One thing that can be a little confusing when you first start using CMake to build your project is the default build type – specified in the CMAKE_BUILD_TYPE variable. CMake has several default build types, but if nothing is specified when configuring your project it defaults to an empty string and no optimization flags are used. A few years ago I wrote some CMake code to set a default if one was not specified, and also populate a list of available options so that it would show up in cmake-gui as a drop down list.

The code snippet above shows a slightly modified version, that I put in a file called BuildType.cmake, and use it to ensure the build type defaults to something reasonable for generators that use it. If you add the directory containing this file to the CMAKE_MODULE_PATH in your project you can then include it somewhere near the top of your CMakeLists.txt. It will now default to using a debug build if the source directory is a git clone, or a release build if not. It is also quite easy to customize its behavior according to the preferences of your project.

If a build type is supplied on the command line that will be respected, and for multi configuration generators (such as Visual Studio) this doesn’t apply (indicated by the presence of the CMAKE_CONFIGURATION_TYPES variable). I have found it useful to develop a few files like this that can easily be dropped into a CMake-based project to provide default settings.

14 Responses to CMake and the Default Build Type

  1. Pingback: Francois Budin

    • Pingback: Marcus D. Hanwell

      • Pingback: Francois Budin

        • Pingback: Marcus D. Hanwell

  2. Pingback: Jean-Christophe Fillion-Robin

  3. Pingback: PaweĊ‚ Bylica

    • Pingback: Marcus D. Hanwell

  4. Pingback: Joe

    • Pingback: Mizux

      • Pingback: Marcus D. Hanwell

  5. Pingback: Cristian Adam

  6. Pingback: Kevin Matthews

    • Pingback: sergio

    • Pingback: epk

Questions or comments are always welcome!

X