Strictly appending to CMAKE_<LANG>_FLAGS

I haven’t been able to identify any mechanism to specify strictly additional compiler flags from a commandline cmake execution. I usually just use -D CMAKE_CXX_FLAGS=foo which in practice works in most cases. However, I have recently encountered an issue using Visual Studio generators where doing so results in the exclusion of CMake-internal default definitions, in particular WIN32.

This is a follow-up to what was originally filed as a GitLab issue. The message closing the issue mentions that the resulting CMAKE_CXX_FLAGS can be “interactively edited after-the-fact in ccmake or cmake-gui” which while true, doesn’t cover our usage of successive executions of a CI job in a non-interactive environment.

Depending on per-execution external criteria (i.e., not encapsulable in CMakeLists.txt) I’m seeking to provide or inhibit compiler flags such as warning-as-error (/WX). This seems to be a case of wanting an “append to default flags” option (without requiring knowledge of what the default flags are), but I haven’t been able to locate such a thing.

Explored alternatives:

  • CXXFLAGS environment variable does yield the desired behavior. This seems to me like inconsistent behavior (possible bug?) for CMAKE_CXX_FLAGS and CXXFLAGS. As I understand the documentation, the environment variable is used to initialize the CMake variable, so using either should yield the same result.

    In either case however, our particular CI jobs in some cases use incremental build areas, which makes the environment variable approach insufficient (since it’s only used during the first configuration).

  • CMAKE_<LANG>_FLAGS_INIT gives the desired behavior, but since I’m not using it from a toolchain file, I’m reluctant to rely on it. It is also relevant for the first configuration and so is similarly insufficient as the environment variable alternative.

I’d certainly argue that the best solution is to ensure that needed definitions are added within the project CMakeLists.txt. Unfortunately, that isn’t reasonable when using with 3rd party libraries. In particular many have a habit of assuming WIN32 (as opposed to _WIN32) since it’s added by default by Visual Studio (and the CMake Visual Studio generators) which leads to sloppy authoring of CMakeLists.txt.

Bump, in particular for feedback on the behavior difference between CXXFLAGS and -D CMAKE_CXX_FLAGS. Based on my understanding this would appear to be a bug (either functionality and/or documentation).