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 that differ just slightly from CMake's (for release, for instance), and I shouldn't have to ask myself "Oh, does their -O3 or our -O2 take precedence when added with add_compile_options."
Now, I know how to set these values, but I don't know how to make them user editable in the two usual ways: by using -DCMAKE_CXX_FLAGS_DEBUG=yourflags
on the command line or by configuring it with ccmake or CMakeSetup.
The problem being that CMAKE sets and caches its own defaults for these, and if you try to overwrite the variables without using FORCE, the "defaults" are never changed. If I use FORCE in my set command: set(CMAKE_CXX_FLAGS_DEBUG blah CACHE STRING "" FORCE)
, it will overwrite it every time the script is run, eliminating the possibility for the user to change it if he wishes.
I managed to hack it to work with CCMAKE by doing the following, but this still doesn't work with cmake -DCMAKE_CXX_FLAGS_DEBUG
as it overwrites the user change AFTER he's done it:
set(DEFAULTS_SET FALSE CACHE BOOL "")
set(CMAKE_CXX_FLAGS_DEBUG "-this -that" CACHE STRING "" FORCE)
set(DEFAULTS_SET TRUE CACHE BOOL "" FORCE)
Obviously, this is a nasty hack and doesn't completely work(in the case of cmake -Dwhatever=thisorthat). I could add other build types as well, but I don't really see why that should be necessary just to change a few simple things.
Edit March 1st, 2015:
I've created a solution that works, though I still am not super thrilled about what I have to do. I'd seen other comments that solve the problem of setting CMAKE_CXX_FLAGS_DEBUG
and friends without having them get clobbered, but this originally didn't work for me because I was trying to also select them based on the compiler that was in use. The compiler isn't determined, however, until it has already filled the variables for me. The trick I used is as follows. You must set the flags variables to something 'special' before the project command.
set(CMAKE_CXX_FLAGS_DEBUG "_UNSET" CACHE STRING "")
project(your_project C CXX)
if(${CMAKE_CXX_FLAGS_DEBUG} STREQUAL "_UNSET")
# Do some compiler switching here and then set your flags with FORCE.
set(CMAKE_CXX_FLAGS_DEBUG "-ggdb3 -O0" CACHE STRING "" FORCE)
endif()
This now allows me to choose defaults that are completely override-able via command line with -D or in cmake-gui.