title: How to create a CMake variable that takes a default value unless explicitly overridden?
body: <p>I have a C++ project that is built using CMake. I would like the build configuration in CMakeLists.txt to be such that it builds in <code>Release</code> mode by default, and builds in <code>Debug</code> mode only when explicitly specified.</p>
  
  <p>Referring to <a href="https://cmake.org/cmake/help/v3.11/command/set.html" rel="noreferrer">this</a> and <a href="https://stackoverflow.com/a/19911494/5987698">this</a>, to allow the build type to be specified from the command line, I have set the variable as follows:</p>
  
  <pre><code>set(CMAKE_BUILD_TYPE Release CACHE STRING "")
  </code></pre>
  
  <p>However, this caches the build type from the last build, so if the last build was <code>Debug</code>, I need to explicitly specify <code>Release</code> in the next build.</p>
  
  <p>I tried using <code>FORCE</code> and also tried adding</p>
  
  <pre><code>unset(CMAKE_BUILD_TYPE CACHE)
  </code></pre>
  
  <p>before the <code>set()</code>, but both these methods fix the value to <code>Release</code> and override the value specified by the user.</p>
  
  <p>Is there a way to achieve this? Thank you.</p>
  
  <hr>
  
  <p>The following is an MCVE:</p>
  
  <p>CMakeLists.txt</p>
  
  <pre><code>cmake_minimum_required(VERSION 3.10)
  set(CMAKE_CXX_STANDARD 11)
  project(Test LANGUAGES CXX)
  
  set(CMAKE_BUILD_TYPE Release CACHE STRING "")
  set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -DDEBUG")
  
  file(GLOB SOURCES *.cpp)
  
  add_executable(test ${SOURCES})
  </code></pre>
  
  <p>test.cpp</p>
  
  <pre><code>#include &lt;iostream&gt;
  
  int main() {
  #ifdef DEBUG
      std::cout &lt;&lt; "Debug defined" &lt;&lt; std::endl;
  #else
      std::cout &lt;&lt; "Debug not defined" &lt;&lt; std::endl;
  #endif
      return 0;
  }
  </code></pre>
  
  <p>To build, I use</p>
  
  <pre><code>cmake .
  make
  </code></pre>
  
  <p>The first step could have <code>-DCMAKE_BUILD_TYPE=Debug</code> for <code>Debug</code> mode.</p>