Skip to content

Commit

Permalink
Merge pull request #8851 from compnerd/msvc-runtime-library
Browse files Browse the repository at this point in the history
cmake: support `MSVC_RUNTIME_LIBRARY` property
  • Loading branch information
haberman committed Aug 28, 2021
2 parents d6b6fdd + c47adad commit f79f956
Showing 1 changed file with 26 additions and 14 deletions.
40 changes: 26 additions & 14 deletions cmake/CMakeLists.txt
Expand Up @@ -15,6 +15,10 @@ endif ()
if(POLICY CMP0048)
cmake_policy(SET CMP0048 NEW)
endif()
# MSVC runtime library flags are selected by an abstraction.
if(POLICY CMP0091)
cmake_policy(SET CMP0091 NEW)
endif()

# Project
project(protobuf C CXX)
Expand Down Expand Up @@ -176,20 +180,28 @@ if (protobuf_BUILD_SHARED_LIBS)
set(protobuf_SHARED_OR_STATIC "SHARED")
else (protobuf_BUILD_SHARED_LIBS)
set(protobuf_SHARED_OR_STATIC "STATIC")
# In case we are building static libraries, link also the runtime library statically
# so that MSVCR*.DLL is not required at runtime.
# https://msdn.microsoft.com/en-us/library/2kzt1wy3.aspx
# This is achieved by replacing msvc option /MD with /MT and /MDd with /MTd
# http://www.cmake.org/Wiki/CMake_FAQ#How_can_I_build_my_MSVC_application_with_a_static_runtime.3F
if (MSVC AND protobuf_MSVC_STATIC_RUNTIME)
foreach(flag_var
CMAKE_CXX_FLAGS CMAKE_CXX_FLAGS_DEBUG CMAKE_CXX_FLAGS_RELEASE
CMAKE_CXX_FLAGS_MINSIZEREL CMAKE_CXX_FLAGS_RELWITHDEBINFO)
if(${flag_var} MATCHES "/MD")
string(REGEX REPLACE "/MD" "/MT" ${flag_var} "${${flag_var}}")
endif(${flag_var} MATCHES "/MD")
endforeach(flag_var)
endif (MSVC AND protobuf_MSVC_STATIC_RUNTIME)
# The CMAKE_<LANG>_FLAGS(_<BUILD_TYPE>)? is meant to be user controlled.
# Prior to CMake 3.15, the MSVC runtime library was pushed into the same flags
# making programmatic control difficult. Prefer the functionality in newer
# CMake versions when available.
if(CMAKE_VERSION VERSION_GREATER_EQUAL 3.15)
set(CMAKE_MSVC_RUNTIME_LIBRARY MultiThreaded$<$<CONFIG:Debug>:Debug>)
else()
# In case we are building static libraries, link also the runtime library statically
# so that MSVCR*.DLL is not required at runtime.
# https://msdn.microsoft.com/en-us/library/2kzt1wy3.aspx
# This is achieved by replacing msvc option /MD with /MT and /MDd with /MTd
# http://www.cmake.org/Wiki/CMake_FAQ#How_can_I_build_my_MSVC_application_with_a_static_runtime.3F
if (MSVC AND protobuf_MSVC_STATIC_RUNTIME)
foreach(flag_var
CMAKE_CXX_FLAGS CMAKE_CXX_FLAGS_DEBUG CMAKE_CXX_FLAGS_RELEASE
CMAKE_CXX_FLAGS_MINSIZEREL CMAKE_CXX_FLAGS_RELWITHDEBINFO)
if(${flag_var} MATCHES "/MD")
string(REGEX REPLACE "/MD" "/MT" ${flag_var} "${${flag_var}}")
endif(${flag_var} MATCHES "/MD")
endforeach(flag_var)
endif (MSVC AND protobuf_MSVC_STATIC_RUNTIME)
endif()
endif (protobuf_BUILD_SHARED_LIBS)

if (MSVC)
Expand Down

0 comments on commit f79f956

Please sign in to comment.