fix(cmake): do not override a parent-set CMAKE_MSVC_RUNTIME_LIBRARY (#28525)

When protobuf is built as a static library through add_subdirectory or FetchContent, its top-level CMakeLists.txt set CMAKE_MSVC_RUNTIME_LIBRARY unconditionally, overriding a value the enclosing project had already set. A parent that forces /MD in every configuration (CMAKE_MSVC_RUNTIME_LIBRARY=MultiThreadedDLL) would still get /MDd for the protobuf and Abseil targets in Debug, causing LNK2038 runtime-library mismatches (MDd_DynamicDebug vs MD_DynamicRelease).

This guards the assignment with `if (NOT DEFINED CMAKE_MSVC_RUNTIME_LIBRARY)`, so protobuf only picks a runtime library when the parent has not. Standalone builds are unchanged: with no parent value set, the same default is chosen from protobuf_MSVC_STATIC_RUNTIME as before.

Fixes #23173.

Test plan: the change is CMake logic, verified with cmake -P (no build needed). Modeling the guarded block, a pre-set CMAKE_MSVC_RUNTIME_LIBRARY is preserved (parent value wins), while an unset one still resolves to the static or DLL default per protobuf_MSVC_STATIC_RUNTIME. Reconfiguring the tree with cmake -S . -B build -G Ninja succeeds, confirming no syntax regression.

Closes #28525

COPYBARA_INTEGRATE_REVIEW=https://github.com/protocolbuffers/protobuf/pull/28525 from yashanil98:fix/issue-23173-msvc-runtime-override 13501be37c
PiperOrigin-RevId: 964437666
This commit is contained in:
yashanil98 2026-08-13 20:03:52 -07:00 committed by Copybara-Service
parent 5d9ce4859e
commit 6ac0b13685

View file

@ -238,10 +238,17 @@ if (protobuf_BUILD_SHARED_LIBS)
else (protobuf_BUILD_SHARED_LIBS)
set(protobuf_SHARED_OR_STATIC "STATIC")
set(ABSL_MSVC_STATIC_RUNTIME ${protobuf_MSVC_STATIC_RUNTIME})
if (protobuf_MSVC_STATIC_RUNTIME)
set(CMAKE_MSVC_RUNTIME_LIBRARY MultiThreaded$<$<CONFIG:Debug>:Debug>)
else()
set(CMAKE_MSVC_RUNTIME_LIBRARY MultiThreaded$<$<CONFIG:Debug>:Debug>DLL)
# Only choose an MSVC runtime library if the enclosing project has not already
# set one. When protobuf is consumed via add_subdirectory/FetchContent, the
# parent may set CMAKE_MSVC_RUNTIME_LIBRARY explicitly (for example to force
# /MD in every configuration); overriding it here causes runtime-library
# mismatches such as LNK2038 (MDd_DynamicDebug vs MD_DynamicRelease).
if (NOT DEFINED CMAKE_MSVC_RUNTIME_LIBRARY)
if (protobuf_MSVC_STATIC_RUNTIME)
set(CMAKE_MSVC_RUNTIME_LIBRARY MultiThreaded$<$<CONFIG:Debug>:Debug>)
else()
set(CMAKE_MSVC_RUNTIME_LIBRARY MultiThreaded$<$<CONFIG:Debug>:Debug>DLL)
endif()
endif()
endif (protobuf_BUILD_SHARED_LIBS)