Trying to follow best practice as suggested in this post, I'd like to set optional flags in the preset file and required flags in the toolchain/CMakelist. To be specific CMAKE_x_FLAGS, but I think this question applies to any other cache variable.
Toolchain file
set(CMAKE_CXX_FLAGS_INIT "-mthumb -mcpu=cortex-m4")
CMakeLists.txt
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fno-exceptions")
CMakePresets.json
{
"version": 3,
"configurePresets": [
{
"name": "debug",
"generator": "Ninja",
"binaryDir": "${sourceDir}/build/${presetName}",
"toolchainFile": "${sourceDir}/cmake/toolchain.cmake",
"cacheVariables": {
"CMAKE_EXPORT_COMPILE_COMMANDS": "ON",
"CMAKE_BUILD_TYPE": "Debug",
"CMAKE_CXX_FLAGS": "-Wall -Wextra"
}
}
]
}
My expectation, as described in the linked post, was that the preset variable is appended to the already specified variables. However, the flags specified in the Toolchain file are overwritten.
-Wall -Wextra -fno-exceptions
This can be prevented by the following line in the CMakeLists.txt
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS_INIT} ${CMAKE_CXX_FLAGS} -fno-exceptions")
Seems to me this is not the way it should work? So my question is, how should I manage CMAKE_CXX_FLAGS(_INIT) from the various files with the following idea?
- Toolchain specific flags in the toolchain file.
- Project specific flags in the CMakeLists.txt.
- Optional, warning flags in the CMakePresets.json file.
The better practice is using
add_compile_options()in CMakeLists.txt.CMAKE_LANG_FLAGS: