I have a C++ project which uses CMake as its build system. I'd like the following behavior:
If cmake is invoked as cmake ..
, then CMAKE_CXX_FLAGS
is -O3 -Wall -Wextra
If cmake is invoked as cmake .. -DCMAKE_BUILD_TYPE=Debug
, then CMAKE_CXX_FLAGS
is -g -Wall -Wextra
I tried the following
message(STATUS "Build type: ${CMAKE_BUILD_TYPE}")
set(CMAKE_CXX_STANDARD 14)
set(CMAKE_CXX_FLAGS "-O3 -Wall -Wextra")
set(CMAKE_CXX_FLAGS_DEBUG "-g -Wall -Wextra")
But this has a big problem. First of all, if the second invocation is used, then both -O3
and -g
flags are passed to the compiler. Besides, if I use the second invocation and the first thereafter, CMAKE_BUILD_TYPE
stays Debug
although not explicitly ordered so - so I get a Debug build although I want an optimized build.
Why? What can I do to get the desired behavior?