Compile with /MT instead of /MD using CMake

You can modify the CMAKE_CXX_FLAGS_<Build Type> and/or CMAKE_C_FLAGS_<Build Type> variables:

set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} /MT")
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} /MTd")

If your CMake flags already contain /MD, you can ensure that the above commands are executed after the point at which /MD is inserted (the later addition of /MT overrides the conflicting existing option), or you can set the flags from scratch:

set(CMAKE_CXX_FLAGS_RELEASE "/MT")
set(CMAKE_CXX_FLAGS_DEBUG "/MTd")

Or alternatively, you could replace the existing /MD and /MDd values with /MT and /MTd respectively by doing something like:

set(CompilerFlags
        CMAKE_CXX_FLAGS
        CMAKE_CXX_FLAGS_DEBUG
        CMAKE_CXX_FLAGS_RELEASE
        CMAKE_C_FLAGS
        CMAKE_C_FLAGS_DEBUG
        CMAKE_C_FLAGS_RELEASE
        )
foreach(CompilerFlag ${CompilerFlags})
  string(REPLACE "/MD" "/MT" ${CompilerFlag} "${${CompilerFlag}}")
endforeach()

CMake finally added proper support for this in version 3.15 with the MSVC_RUNTIME_LIBRARY target property:

cmake_minimum_required(VERSION 3.15)
cmake_policy(SET CMP0091 NEW)
project(my_project)

add_executable(foo foo.c)
set_property(TARGET foo PROPERTY
             MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")

You can also specify a global default by setting the CMAKE_MSVC_RUNTIME_LIBRARY variable instead.

Tags:

Cmake