# CMake 错误：不允许源内构建。请从源目录中删除 CMakeCache.txt 文件。

- **ID:** `cmake/in-source-build-forbidden`
- **领域:** cmake
- **类别:** build_error
- **验证级别:** ai_generated
- **修复率:** 95%

## 根因

CMake 配置为禁止在源码目录内直接构建，但构建目录与源码目录相同。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 3.13 | active | — | — |
| 3.18 | active | — | — |
| 3.20 | active | — | — |
| 3.25 | active | — | — |
| 3.27 | active | — | — |

## 解决方案

1. ```
   创建一个单独的构建目录并从那里运行 cmake：mkdir build && cd build && cmake .. && make
   ```
2. ```
   如果必须进行源内构建，请在 CMakeLists.txt 开头设置策略：cmake_policy(SET CMP0011 OLD)，但不建议用于生产环境。
   ```
3. ```
   使用 cmake -B <构建目录> -S <源码目录> 明确分离目录：cmake -B build -S . && cmake --build build
   ```

## 无效尝试

- **Deleting CMakeCache.txt and re-running cmake . in the source directory** — Deleting the cache file alone does not change the build directory location; the next cmake invocation still uses the source directory as the build directory, triggering the same error. (90% 失败率)
- **Setting CMAKE_DISABLE_IN_SOURCE_BUILD to OFF via command line** — This policy is typically enforced by the project's CMakeLists.txt via cmake_policy(SET CMP0011 NEW) or a project-specific guard, so overriding it externally does not work. (85% 失败率)
- **Adding a CMakeLists.txt in the build directory** — The build directory is not supposed to contain a CMakeLists.txt; CMake expects to find it in the source directory. This approach confuses the build system and leads to other errors. (95% 失败率)
