CMake 错误:不允许源内构建。请从源目录中删除 CMakeCache.txt 文件。
CMake Error: In-source builds are not allowed. Please remove the CMakeCache.txt file from the source directory.
ID: cmake/in-source-build-forbidden
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.13 | active | — | — | — |
| 3.18 | active | — | — | — |
| 3.20 | active | — | — | — |
| 3.25 | active | — | — | — |
| 3.27 | active | — | — | — |
根因分析
CMake 配置为禁止在源码目录内直接构建,但构建目录与源码目录相同。
English
CMake is configured to forbid building directly in the source tree, but the build directory is the same as the source directory.
官方文档
https://cmake.org/cmake/help/latest/policy/CMP0011.html解决方案
-
创建一个单独的构建目录并从那里运行 cmake:mkdir build && cd build && cmake .. && make
-
如果必须进行源内构建,请在 CMakeLists.txt 开头设置策略:cmake_policy(SET CMP0011 OLD),但不建议用于生产环境。
-
使用 cmake -B <构建目录> -S <源码目录> 明确分离目录:cmake -B build -S . && cmake --build build
无效尝试
常见但无效的做法:
-
Deleting CMakeCache.txt and re-running cmake . in the source directory
90% 失败
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.
-
Setting CMAKE_DISABLE_IN_SOURCE_BUILD to OFF via command line
85% 失败
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.
-
Adding a CMakeLists.txt in the build directory
95% 失败
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.