The default settings for the compiler are selected from the 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. For example, for Visual Studio 2017, CMake will load the default settings from the Windows-MSVC.cmake and the language settings from Windows-MSVC-C.cmake or Windows-MSVC-CXX.cmake .
To check the default settings, create the CompilerOptions.cmake file 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 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 a project is configured when opening a directory in Visual Studio 2017, the following information will be displayed in the IDE 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 ...
Thus, the warning option /W3 is selected from the CMake variable CMAKE_CXX_FLAGS_INIT , which is then applied to all CMake targets generated in the project.
To control the warning level on a CMake project or target level, you can change the CMAKE_CXX_FLAGS_INIT variable in 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()
Then the warning flags can be controlled by setting the target compilation 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 settings in the override file instead of manually setting variables such as CMAKE_CXX_FLAGS .
When making changes to the CompilerOptions.cmake file, you must recreate the build folder. When using Visual Studio 2017 in Open Folder mode, select the Cache ... -> Delete Cache Folders command in the CMake menu, and then Cache ... -> Generate in the CMake menu to recreate the build folder.