# CMake 错误：导出目标 "mylib" 时策略范围不匹配。未设置策略 CMP0074。

- **ID:** `cmake/exported-target-policy-scope-mismatch`
- **领域:** cmake
- **类别:** build_error
- **错误码:** `CMP0074`
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

通过 install(EXPORT) 或 export() 导出目标时，目标目录级别的策略设置与导入项目的策略范围不同，导致 CMake 拒绝导出以防止行为不一致。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| CMake 3.12 | active | — | — |
| CMake 3.18 | active | — | — |
| CMake 3.22 | active | — | — |

## 解决方案

1. ```
   通过在导出和导入项目的顶层 CMakeLists.txt 中在任何目标创建之前添加 `cmake_policy(SET CMP0074 NEW)`，确保两个项目中策略 CMP0074 都设置为 NEW。
   ```
2. ```
   在目标定义周围使用 `cmake_policy(PUSH)` 和 `cmake_policy(POP)` 隔离策略设置，确保导出看到与导入项目相同的作用域。
   ```
3. ```
   使用 `export(TARGETS mylib FILE "${CMAKE_BINARY_DIR}/MyLibConfig.cmake")` 重新生成导出配置文件，在调用 export() 之前设置一致的策略。
   ```

## 无效尝试

- **Using cmake_policy(SET CMP0074 OLD) to force old behavior** — Setting cmake_policy(SET CMP0074 OLD) in the exporting project may suppress the error but can lead to subtle build failures in the importing project. (65% 失败率)
- **Removing export() or install(EXPORT) from CMakeLists.txt** — Removing the export() call entirely avoids the error but breaks the intended package distribution. (90% 失败率)
- **Manually duplicating target definition in importing project** — Copying the target's CMakeLists.txt into the importing project manually may resolve the immediate error but creates maintenance burden and duplicates code. (80% 失败率)
