Skip to content

Commit

Permalink
cmake: support MSVC_RUNTIME_LIBRARY property
Browse files Browse the repository at this point in the history
When using a new enough CMake (3.15+) prefer to use the
`MSVC_RUNTIME_LIBRARY` property on targets to select the runtime
library variant.  This property is automatically set to the value
specified by `CMAKE_MSVC_RUNTIME_LIBRARY`.  This proper requires that
the CMake Policy 91 is set to new (see CMP0091).
  • Loading branch information
compnerd committed Jul 31, 2021
1 parent 914c6fe commit 77f5402
Showing 1 changed file with 18 additions and 14 deletions.
32 changes: 18 additions & 14 deletions cmake/CMakeLists.txt
Expand Up @@ -176,20 +176,24 @@ 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)
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 77f5402

Please sign in to comment.