Statically Link to MSVC Runtime Library using CMake

Statically Link to MSVC Runtime Library using CMake

When building applications on Windows, it is sometimes necessary to link the MSVC runtime library statically. This ensures that the application does not rely on external runtime DLLs at execution, which can simplify deployment and reduce dependency issues. This tutorial explains how to statically link to MSVC runtime library using CMake.

In CMake, the MSVC_RUNTIME_LIBRARY property controls how the runtime library is linked for a target. Setting this property to the MultiThreaded option (or MultiThreadedDebug for debug builds) forces static linking of the runtime library when using the MSVC compiler.

A minimal CMakeLists.txt demonstrating how to use the configuration property:

cmake_minimum_required(VERSION 3.27)
project(myapp)

set(CMAKE_CXX_STANDARD 17)

add_executable(${PROJECT_NAME} main.cpp)

if (MSVC)
    set_property(TARGET ${PROJECT_NAME}
            PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
endif ()

In this setup, static linking is applied only when the MSVC compiler is detected. For debug builds, the Debug variant of the static runtime library is used, while release builds default to the standard static runtime.

Leave a Comment

Cancel reply

Your email address will not be published.