From 6ac0b13685e04b660c5df287228878dd104392f7 Mon Sep 17 00:00:00 2001 From: yashanil98 <79158725+yashanil98@users.noreply.github.com> Date: Thu, 13 Aug 2026 20:03:52 -0700 Subject: [PATCH] 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 13501be37c13359e11b0d9573bc24e407758cd2f PiperOrigin-RevId: 964437666 --- CMakeLists.txt | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 2e338466f8..1b482ab13c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -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$<$:Debug>) - else() - set(CMAKE_MSVC_RUNTIME_LIBRARY MultiThreaded$<$: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$<$:Debug>) + else() + set(CMAKE_MSVC_RUNTIME_LIBRARY MultiThreaded$<$:Debug>DLL) + endif() endif() endif (protobuf_BUILD_SHARED_LIBS)