在VSCode中使用CMake配置PyTorch C++ API的问题排查
问题描述
我运行PyTorch C++ API的最小示例,在macOS下用以下命令手动编译可正常运行:
mkdir build cd build cmake -DCMAKE_PREFIX_PATH=/absolute/path/to/libtorch .. cmake --build . --config Release
但在VSCode中按官方文档配置时,出现CMake错误:
CMake Error at CMakeLists.txt:4 (find_package):
By not providing "FindTorch.cmake" in CMAKE_MODULE_PATH this project has
asked CMake to find a package configuration file provided by "Torch", but
CMake did not find one.Could not find a package configuration file provided by "Torch" with any of
the following names:TorchConfig.cmake
torch-config.cmakeAdd the installation prefix of "Torch" to CMAKE_PREFIX_PATH or set
"Torch_DIR" to a directory containing one of the above files. If "Torch"
provides a separate development package or SDK, be sure it has been
installed.
尝试在CMakeLists.txt中添加以下命令无效:
set(CMAKE_MODULE_PATH "/Users/myusername/external_library_include/libtorch") include_directories("/Users/myusername/external_library_include/libtorch")
解决方法
以下是在VSCode中配置CMAKE_PREFIX_PATH的几种有效方式:
方法1:通过CMake Tools扩展的UI配置
- 打开VSCode命令面板(快捷键:
Cmd+Shift+P) - 输入并选择
CMake: Edit User-Local CMake Kits - 在打开的
cmake-kits.json文件中,找到对应你当前使用的编译器的kit(比如Clang),在cmakeSettings节点下添加CMAKE_PREFIX_PATH配置:
{ "name": "Clang", "compilers": { "C": "/usr/bin/clang", "CXX": "/usr/bin/clang++" }, "cmakeSettings": { "CMAKE_PREFIX_PATH": "/Users/myusername/external_library_include/libtorch" } }
- 保存文件后,执行命令面板的
CMake: Configure重新生成配置
方法2:修改VSCode全局settings.json
- 打开VSCode设置(快捷键:
Cmd+,) - 搜索
cmake.configureArgs,点击编辑 in settings.json - 将
-DCMAKE_PREFIX_PATH参数加入配置数组:
"cmake.configureArgs": [ "-DCMAKE_PREFIX_PATH=/Users/myusername/external_library_include/libtorch" ]
- 保存设置后重新执行CMake配置
方法3:直接在CMakeLists.txt中指定Torch_DIR(最直接)
不需要修改CMAKE_MODULE_PATH,直接把Torch_DIR指向libtorch中包含TorchConfig.cmake的目录(通常是libtorch/share/cmake/Torch):
set(Torch_DIR "/Users/myusername/external_library_include/libtorch/share/cmake/Torch") find_package(Torch REQUIRED)
这样CMake能直接定位到配置文件,无需额外设置CMAKE_PREFIX_PATH
内容的提问来源于stack exchange,提问作者MOON

