I would like to change the default values for CMAKE_CXX_FLAGS_RELEASE
or CMAKE_CXX_FLAGS_DEBUG
in CMake. Basically, I have some project defaults th
I just wanted to add the four possibilities I see:
Having your own toolchain files containing the presets for each compiler you support like:
GNUToolchain.cmake
set(CMAKE_CXX_FLAGS_DEBUG "-ggdb3 -O0" CACHE STRING "")
And then use it with
cmake -DCMAKE_TOOLCHAIN_FILE:string=GNUToolchain.cmake ...
You can try to determine the compiler by checking CMAKE_GENERATOR (which is valid before the project() command):
CMakeLists.txt
if("${CMAKE_GENERATOR}" MATCHES "Makefiles" OR
("${CMAKE_GENERATOR}" MATCHES "Ninja" AND NOT WIN32))
set(CMAKE_CXX_FLAGS_DEBUG "-ggdb3 -O0" CACHE STRING "")
endif()
project(your_project C CXX)
You can use CMAKE_USER_MAKE_RULES_OVERRIDE to give a script with your own ..._INIT
values:
It is loaded after CMake’s builtin compiler and platform information modules have been loaded but before the information is used. The file may set platform information variables to override CMake’s defaults.
MyInitFlags.cmake
# Overwrite the init values choosen by CMake
if (CMAKE_COMPILER_IS_GNUCXX)
set(CMAKE_CXX_FLAGS_DEBUG_INIT "-ggdb3 -O0")
endif()
CMakeLists.txt
set(CMAKE_USER_MAKE_RULES_OVERRIDE "MyInitFlags.cmake")
project(your_project C CXX)
You can simplify your solution from March 1st by checking against the ..._INIT
variants of the compiler flag variables:
CMakeLists.txt
project(your_project C CXX)
if (DEFINED CMAKE_CXX_FLAGS_DEBUG_INIT AND
"${CMAKE_CXX_FLAGS_DEBUG_INIT}" STREQUAL "${CMAKE_CXX_FLAGS_DEBUG}")
# Overwrite the init values choosen by CMake
if (CMAKE_COMPILER_IS_GNUCXX)
set(CMAKE_CXX_FLAGS_DEBUG "-ggdb3 -O0" CACHE STRING "" FORCE)
endif()
endif()
Comments:
I prefer and use the toolchain variant. But I admit it has the disadvantage of having to give the toolchain file manually (if you are not calling cmake
via a script/batch file).
References: