How should I make my CMake project default to configuration for a Release rather than a Debug build?
Have a CMake project default to the Release build type
Asked Answered
You could try the following:
if (NOT EXISTS ${CMAKE_BINARY_DIR}/CMakeCache.txt)
if (NOT CMAKE_BUILD_TYPE)
set(CMAKE_BUILD_TYPE "Release" CACHE STRING "" FORCE)
endif()
endif()
Isn't there a simpler way to check for the presence of the cache? –
Caesar
Is this preferable to my now-improved check? –
Caesar
My version sets the default configuration to "Release", i.e. it is done once and only when the user hasn't already set it to anything else. Your version sets the build type to "Release" every time the user enters an empty string. –
Psycho
So, when does the user enter an empty string intentionally? Is this a common workflow? Sorry for nagging about this (and +1). –
Caesar
Maybe for some debugging purposes? In most cases there is probably no need to leave it empty but in case there is, the user should have the freedom. Note that in your initial question you mention the default configuration, i.e., something that is set only once, not every time CMake is run. –
Psycho
It's not leaving it empty, it's setting it empty. But your second point is valid. –
Caesar
I started out with simplistic:
if(NOT CMAKE_BUILD_TYPE)
set(CMAKE_BUILD_TYPE "Release")
endif()
but thanks to @RaulLaasner's suggestions, I now do:
if (NOT CMAKE_BUILD_TYPE OR CMAKE_BUILD_TYPE STREQUAL "")
set(CMAKE_BUILD_TYPE "Release" CACHE STRING "" FORCE)
endif()
and that seems to be more robust.
Edit: Upon later reflection, I've decided to not change the default from within the CMake script itself. Perhaps it's better to leave the default the same as with all other CMake scripts in the world basically.
With your solution, the user must always use "Release", "Debug", or something else, but cannot leave the build type empty, because then it would automatically be set to "Release". Instead, you should test if this is the first time CMake is run and if the build type has not already been set. See my proposed solution. –
Psycho
@RaulLaasner: I don't think so, because
CMAKE_BUILD_TYPE
is cached. –
Caesar It's cached yes but if it's an empty string, then
NOT CMAKE_BUILD_TYPE
evaluates to true. –
Psycho @RaulLaasner: So I could just add a comparison to the empty string then? –
Caesar
You mean something like
(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_BUILD_TYPE STREQUAL "")
? Indeed, that also seems to work. –
Psycho The second
NOT
is missing in your conditional. –
Psycho @RaulLaasner: Why? If it's an empty string then I want to set it to Release. Note I'm using an OR. –
Caesar
Well your initial question was about just the default configuration. In the current form, the build type is set to "Release" whenever it is equal to "", even if the user intends to keep it empty. –
Psycho
© 2022 - 2024 — McMap. All rights reserved.