CMake 报 Cannot find source file 或 No SOURCES given to target 怎么办?

dajinli 2026-05-01 09:00 2 浏览

代码拆分重构后,CMakeLists.txt 的源文件列表没有同步更新,add_executable 找不到 .cpp,甚至出现 No SOURCES given to target。

报错信息

CMake Error at CMakeLists.txt:xx (add_executable):
  Cannot find source file: src/xxx.cpp
CMake Error at CMakeLists.txt:xx (add_executable):
  No SOURCES given to target: xxx

原因

  • 代码拆分重构后,CMakeLists.txt 中的源文件列表未同步更新。
  • 源文件实际路径、文件名与 CMake 配置不匹配。
  • 文件存放目录错误,编译器按路径找不到文件。

解决

  1. 核对源文件实际位置与文件名拼写。
  2. 在 add_executable 中补充所有拆分后的 .cpp 源文件。
  3. 删除 build 目录,重新执行 cmake + make。

预防

改完目录结构或拆分文件后,第一时间同步 CMakeLists.txt;不要带着旧配置继续编译。