First: the recommended use of CMake should always specify CMAKE_BUILD_TYPE explicitly on the command line (if and only if a generator with one configuration is used). Your use case deviates from this best practice, so consider this answer as โhow you can do it,โ not necessarily as โhow you should do it.โ
To solve the first problem, you should be able to do this at the beginning of your CMakeList:
if(NOT CMAKE_BUILD_TYPE) set(CMAKE_BUILD_TYPE Release) endif() set(CMAKE_CXX_FLAGS "-Wall -Wextra") set(CMAKE_CXX_FLAGS_DEBUG "-g") set(CMAKE_CXX_FLAGS_RELEASE "-O3")
This will make sure that if you do not specify the type of assembly at all, โReleaseโ will be selected by default, and thus CMAKE_CXX_FLAGS_RELEASE will be used.
The second is harder to solve. Variables passed from the command line (for example, CMAKE_BUILD_TYPE=Debug ) are cached by CMake and therefore reused in subsequent calls (which is necessary since CMake can re-run itself if you change its inputs between assemblies).
The only solution is to get the user to switch the build type again using cmake .. -DCMAKE_BUILD_TYPE=Release .
Think about why this is necessary: โโas I said, CMake can rerun itself as part of the assembly if the CMake input ( CMakeLists.txt files or their dependencies) has changed since the last CMake was launched. In this case, it will also start without command line arguments such as -DCMAKE_BUILD_TYPE=whatever , and will rely on the cache to provide the same value as the last time. This scenario is indistinguishable from the fact that you manually run cmake .. with no additional arguments.
I could provide a hacker solution to always reset CMAKE_BUILD_TYPE to Release , unless explicitly indicated on the command line. However, this would also mean that the assembly generated as Debug would be regenerated as Release if automatic regeneration occurred. I am sure that is not what you want.
Angew source share