# CMake 错误：未设置策略 CMP0091：MSVC 运行时库标志由 CMAKE_MSVC_RUNTIME_LIBRARY 变量选择。

- **ID:** `cmake/missing-override-policy-visibility-inline`
- **领域:** cmake
- **类别:** config_error
- **错误码:** `CMP0091`
- **验证级别:** ai_generated
- **修复率:** 90%

## 根因

CMake 3.15+ 引入了 CMP0091 策略，通过 CMAKE_MSVC_RUNTIME_LIBRARY 变量控制 MSVC 运行时库的选择，但未显式设置该策略，导致静默回退到旧行为，可能与项目预期不匹配。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| CMake 3.15 | active | — | — |
| CMake 3.16 | active | — | — |
| CMake 3.20 | active | — | — |
| Visual Studio 2019 | active | — | — |
| Visual Studio 2022 | active | — | — |

## 解决方案

1. ```
   在顶层 CMakeLists.txt 中的任何 project() 调用之前添加 `cmake_policy(SET CMP0091 NEW)`，然后将 CMAKE_MSVC_RUNTIME_LIBRARY 设置为所需值（例如 MultiThreadedDLL）。
   ```
2. ```
   在工具链文件中使用 `set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreadedDLL")` 和 `cmake_policy(SET CMP0091 NEW)` 进行跨平台构建。
   ```
3. ```
   如果使用 CMake 3.14 或更早版本，升级到 3.15+ 并采用新策略；否则，避免使用 CMAKE_MSVC_RUNTIME_LIBRARY，依赖手动标志管理。
   ```

## 无效尝试

- **Setting CMAKE_MSVC_RUNTIME_LIBRARY directly without cmake_policy(SET CMP0091 NEW)** — Manually setting CMAKE_MSVC_RUNTIME_LIBRARY without setting the policy may still produce the warning or error, as the policy governs whether the variable is honored. (70% 失败率)
- **Hardcoding MSVC runtime flags in CMAKE_CXX_FLAGS** — Adding /MD or /MT flags manually via CMAKE_CXX_FLAGS can conflict with CMake's runtime library selection, causing linker errors or undefined behavior. (85% 失败率)
- **Suppressing the warning with cmake_policy(SET CMP0091 OLD)** — Ignoring the warning may allow the build to proceed, but the resulting binaries may link against mismatched runtime libraries, leading to crashes. (60% 失败率)
