27

Visual Studio 2017 comes with full CMake integration. To learn about this combination, I was starting with this basic sample:

# CMakeLists.txt
cmake_minimum_required(VERSION 3.8)
project(foo)
add_executable(foo foo.cpp)

and

// foo.cpp
int main() {}

This properly generates build scripts, and compiles and links with no issues. That was easy.

Trying to set compiler options, on the other hand, turned out to be anything but trivial. In my case I was attempting to set the warning level to 4.

The obvious solution

add_compile_options("/W4")

didn't pan out as expected. The command line passed to the compiler now contains both /W4 (as intended) as well as /W3 (picked up from somewhere else), producing the following warning:

cl : Command line warning D9025: overriding '/W3' with '/W4'

To work around this, I would need to replace any incompatible compiler option(s) instead of just adding one. CMake does not provide any immediate support for this, and the standard solution (as this Q&A suggests) seems to be:

if(CMAKE_CXX_FLAGS MATCHES "/W[0-4]")
    string(REGEX REPLACE "/W[0-4]" "/W4" CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}")
else()
    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /W4")
endif()

This, however, has two issues:

  • It sets the global CMAKE_CXX_FLAGS, applying to all C++ targets. This may not be intended (not an issue for me right now).
  • It doesn't scale. For every compiler option to add, you would have to read up on incompatible options, and manually strip those first. This will inevitably fail1.

My question is two-fold:

  1. Where does the CMake integration pick up default settings from, and can this be controlled?
  2. How do you set compiler options in general? (If this is too broad a topic, I'd be happy for help on setting the warning level only.)


1 Incidentally, the solution I replicated fails to account for the /Wall option, that is incompatible with /W4 as well.
IInspectable
  • 46,945
  • 8
  • 85
  • 181
  • Some compiler options can be changed by cross-platform-compatible CMake variables or properties. But warning levels unfortunately don't have those generic way of defining them. You may want to take a look at the work of @ruslo found [here](https://github.com/ruslo/sugar/wiki/Cross-platform-warning-suppression) and the discussion about extending CMake itself [here](https://cmake.org/pipermail/cmake-developers/2016-March/028107.html). – Florian Sep 01 '17 at 08:54
  • @Florian: Thanks for the confirmation, that CMake does not directly support setting the warning level. Still, the links you posted are not immediately helpful to me: Ruslo's work only supports setting `/Wall`, while the second link works by tweaking `CMAKE_CXX_FLAGS`. The [answer](https://stackoverflow.com/a/46000520/1889329) posted by @sakra to override the default compiler options looks like a cleaner solution, allowing more fine-grained control over setting compiler options. – IInspectable Sep 02 '17 at 06:03
  • 1
    When I was working on an answer for [this question](https://stackoverflow.com/questions/45955272/modern-way-to-set-compiler-flags-in-cross-platform-cmake-project) I noticed that `add_compile_options()` command does replace/overwrites the warning level specification instead of just appending it to "Additional Options" like when you append to `CMAKE_CXX_FLAGS`. I'm not sure why there is a difference (have to check in CMake's code), but can please give `add_compile_options("/W4")` a try? In my CMake version 3.9 I didn't get that compiler warning anymore. – Florian Sep 11 '17 at 07:29
  • @Florian: `add_compile_options("/W4")` still gives me a compiler warning. I'm using the `"Ninja"` generator, using the CMake support built into Visual Studio 2017 (15.3.3), so there is no .vcxproj generated along the way (as far as I know). This is using `cmake version 3.8.0-MSVC_2`. – IInspectable Sep 11 '17 at 08:44

3 Answers3

33

The default settings for the compiler are picked up from standard module files located in the Modules directory of the CMake installation. The actual module file used depends on both the platform and the compiler. E.g., for Visual Studio 2017, CMake will load the default settings from the file Windows-MSVC.cmake and language specific settings from Windows-MSVC-C.cmake or Windows-MSVC-CXX.cmake.

To inspect the default settings, create a file CompilerOptions.cmake in the project directory with the following contents:

# log all *_INIT variables
get_cmake_property(_varNames VARIABLES)
list (REMOVE_DUPLICATES _varNames)
list (SORT _varNames)
foreach (_varName ${_varNames})
    if (_varName MATCHES "_INIT$")
        message(STATUS "${_varName}=${${_varName}}")
    endif()
endforeach()

Then initialize the CMAKE_USER_MAKE_RULES_OVERRIDE variable in your CMakeLists.txt:

# CMakeLists.txt
cmake_minimum_required(VERSION 3.8)
set (CMAKE_USER_MAKE_RULES_OVERRIDE "${CMAKE_CURRENT_LIST_DIR}/CompilerOptions.cmake")
project(foo)
add_executable(foo foo.cpp)

When the project is configured upon opening the directory using Open Folder in Visual Studio 2017, the following information will be shown in the IDE's output window:

 ...
 -- CMAKE_CXX_FLAGS_DEBUG_INIT= /MDd /Zi /Ob0 /Od /RTC1
 -- CMAKE_CXX_FLAGS_INIT= /DWIN32 /D_WINDOWS /W3 /GR /EHsc
 -- CMAKE_CXX_FLAGS_MINSIZEREL_INIT= /MD /O1 /Ob1 /DNDEBUG
 -- CMAKE_CXX_FLAGS_RELEASE_INIT= /MD /O2 /Ob2 /DNDEBUG
 -- CMAKE_CXX_FLAGS_RELWITHDEBINFO_INIT= /MD /Zi /O2 /Ob1 /DNDEBUG
 ...

So the warning setting /W3 is picked up from the CMake variable CMAKE_CXX_FLAGS_INIT which then applies to all CMake targets generated in the project.

To control the warning level on the CMake project or target level, one can alter the CMAKE_CXX_FLAGS_INIT variable in the CompilerOptions.cmake by adding the following lines to the file:

if (MSVC)
    # remove default warning level from CMAKE_CXX_FLAGS_INIT
    string (REGEX REPLACE "/W[0-4]" "" CMAKE_CXX_FLAGS_INIT "${CMAKE_CXX_FLAGS_INIT}")
endif()

The warning flags can then be controlled by setting the target compile options in CMakeLists.txt:

...
add_executable(foo foo.cpp)
target_compile_options(foo PRIVATE "/W4")

For most CMake projects it makes sense to control the default compiler options in a rules override file instead of manually tweaking variables like CMAKE_CXX_FLAGS.

When making changes to the CompilerOptions.cmake file, it is necessary to recreate the build folder. When using Visual Studio 2017 in Open Folder mode, choose the command Cache ... -> Delete Cache Folders from the CMake menu and then Cache ... -> Generate from the CMake menu to recreate the build folder.

sakra
  • 62,199
  • 16
  • 168
  • 151
  • 2
    Perfect explanation on where the defaults come from, and adjusting the defaults in a single location also looks like a maintainable solution. The script to dump a list of variables and their values is also very helpful. Since I couldn't find any of this previously, I'm going to assume, that there are resources I don't know of. Do you know of any resources (online or books) to learn CMake you could recommend? – IInspectable Sep 01 '17 at 19:03
  • Look at the source code ;-) CMake's source contains interesting information in comments, which unluckily isn't available anywhere else, e.g.: https://github.com/Kitware/CMake/blob/de64329232599553859191b94e2f60fc479045b9/Source/cmGlobalGenerator.cxx#L331 – sakra Sep 03 '17 at 07:27
  • 1
    @sakra That doesn't seem to work in VS2017 15.8. No CMAKE_CXX_FLAGS_ is listed. – Zingam May 14 '18 at 21:40
10

Turning my comment into an answer

CMake does come with some compiler switches preset. For visual studio those are mainly standard link libraries, warning levels, optimization levels, exception handling, debug information and platform specific defines.

What you now have to differentiate when you want to change a CMake generated compiler settings are the following use cases:

  1. Additional compiler flags CMake does not define vs. changing CMake's preset settings
  2. Project default settings vs. project user defined settings

So let's discuss common solutions for those cases.


User changes/adds to Project/CMake Compiler Flags Defaults

The standard way would be to modify the cached compiler flags variables by using tools shipped with CMake like cmake-gui and ccmake.

To achieve this in Visual Studio you would have to:

  • CMake / Cache / View CMakeCache
  • Manually change e.g. CMAKE_CXX_FLAGS to /Wall

    CMakeCache.txt

    //Flags used by the compiler during all build types.
    CMAKE_CXX_FLAGS:STRING= /DWIN32 /D_WINDOWS /Wall /GR /EHsc
    
  • CMake / Cache / Generate


Or you preset the CMAKE_CXX_FLAGS cache variable via a CMakeSettings.json file:

  • CMake / Change CMake Settings

    Force the cache entry with -DCMAKE_CXX_FLAGS:STRING=... in cmakeCommandArgs

    CMakeSettings.json

    {
        // See https://go.microsoft.com//fwlink//?linkid=834763 for more information about this file.
        "configurations": [
            {
                "name": "x86-Debug (all warnings)",
                "generator": "Visual Studio 15 2017",
                "configurationType": "Debug",
                "buildRoot": "${env.LOCALAPPDATA}\\CMakeBuild\\${workspaceHash}\\build\\${name}",
                "cmakeCommandArgs": "-DCMAKE_CXX_FLAGS:STRING=\"/DWIN32 /D_WINDOWS /Wall /GR /EHsc\"",
                "buildCommandArgs": "-m -v:minimal"
            }
        ]
    }
    
  • If you deliver this CMakeSettings.json file with your CMake project it gets permanent


Project changes to CMake Compiler Flags Defaults

If you want to keep most of CMake's compiler flags in place, @sakra's answer is definitely the way to go.

For my VS projects I've put the CXX flag settings into a toolchain file coming with the project itself. Mainly to freeze those settings and don't have a dependency the CMake version used or any environment variables set.

Taking the example from above that would look like:

VS2017Toolchain.cmake

set(CMAKE_CXX_FLAGS "/DWIN32 /D_WINDOWS /Wall /GR /EHsc" CACHE INTERNAL "")

CMakeSettings.json

    {
        // See https://go.microsoft.com//fwlink//?linkid=834763 for more information about this file.
        "configurations": [
            {
                "name": "x86-Debug (all warnings)",
                "generator": "Visual Studio 15 2017",
                "configurationType": "Debug",
                "buildRoot": "${env.LOCALAPPDATA}\\CMakeBuild\\${workspaceHash}\\build\\${name}",
                "cmakeCommandArgs": "-DCMAKE_TOOLCHAIN_FILE:FILEPATH=\"${projectDir}\\VS2017Toolchain.cmake\"",
                "buildCommandArgs": "-m -v:minimal"
            }
        ]
    }

References

Florian
  • 39,996
  • 9
  • 133
  • 149
  • Those are some nice alternatives. Setting the `CMAKE_TOOLCHAIN_FILE` variable is particularly appealing, as it pins down the environment to fixed values, allowing those to be put under source control. Still, it feels a bit like an abuse of what toolchain files are meant to be used for. This introduces changes to CMake's behavior (just like the `CMAKE_USER_MAKE_RULES_OVERRIDE` variable) very early, before CMake builds its first test project. Am I overly concerned, or does this indeed open the potential for issues? (I'm a CMake novice, and my mental model of how CMake works may well be off.) – IInspectable Sep 07 '17 at 11:12
  • 1
    @IInspectable I prefer the toolchain approach also because it separates the different compiler pre-settings very nicely and makes my generic `CMakeLists.txt` files more readable. And no toolchains are not only for cross-compiling, but you can alternatively use the `-C` pre-load cache command line option (toolchains just have the advantage that they also propagate into any projects CMake may generate on the fly). And having the flags right from the beginning has the advantage that the compiler checks (configuration step) would fail if I got them wrong. – Florian Sep 07 '17 at 11:49
5

In CMake 3.15, CMake introduced a fix for this MSVC-specific warning:

cl : Command line warning D9025: overriding '/W3' with '/W4'

and the compiler warning flags (like /W3) are no longer automatically added. So by upgrading to CMake 3.15 or greater, this warning should no longer appear. From the docs:

When using MSVC-like compilers in CMake 3.14 and below, warning flags like /W3 are added to CMAKE_<LANG>_FLAGS by default. This is problematic for projects that want to choose a different warning level programmatically. In particular, it requires string editing of the CMAKE_<LANG>_FLAGS variables with knowledge of the CMake builtin defaults so they can be replaced.

CMake 3.15 and above prefer to leave out warning flags from the value of CMAKE_<LANG>_FLAGS by default.

Along with this fix, CMake introduced policy CMP0092, which allows you to switch back to the OLD behavior (adding the warning flags by default) if necessary.

Community
  • 1
  • 1
Kevin
  • 16,549
  • 8
  • 60
  • 74