CMake 错误:找不到源文件:/path/to/src/module.cpp。已尝试扩展名 .c .C .c++ .cc .cpp .cxx .cu .m .M .mm .h .hh .h++ .hm .hpp .hxx .in .txx .f .f90 .F .F90 .s .S .asm
CMake Error: Cannot find source file: /path/to/src/module.cpp. Tried extensions .c .C .c++ .cc .cpp .cxx .cu .m .M .mm .h .hh .h++ .hm .hpp .hxx .in .txx .f .f90 .F .F90 .s .S .asm
ID: cmake/source-file-not-found-alternate-extensions
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.20 | active | — | — | — |
| 3.22 | active | — | — | — |
| 3.24 | active | — | — | — |
| 3.26 | active | — | — | — |
| 3.28 | active | — | — | — |
根因分析
add_executable() 或 add_library() 中列出的源文件在磁盘上不存在。常见原因:文件被移动、重命名、删除,或路径相对于错误的目录。
English
The source file listed in add_executable() or add_library() does not exist on disk. Common causes: file was moved, renamed, deleted, or the path is relative to a wrong directory.
官方文档
https://cmake.org/cmake/help/latest/command/add_executable.html解决方案
-
验证文件是否存在于确切路径。使用绝对路径或从 CMAKE_CURRENT_SOURCE_DIR 开始的正确相对路径。示例: set(MY_SRC ${CMAKE_CURRENT_SOURCE_DIR}/src/module.cpp) add_executable(myapp ${MY_SRC}) -
如果文件已被移动,更新 CMakeLists.txt 指向新位置。修复后运行 'cmake --build . --clean-first'。
-
如果使用生成的文件,确保在定义目标之前生成它们。使用带 OUTPUT 的 add_custom_command,并将输出添加到目标的源文件中。
无效尝试
常见但无效的做法:
-
60% 失败
The stale CMake cache may still reference the old path, causing the same error. A full reconfigure is needed.
-
90% 失败
The error is about a missing source file, not about target existence. Adding to another target doesn't create the missing file.
-
75% 失败
If the file doesn't exist on disk, no extension change will help. The file must be present and the path must match exactly.