Could not find a package configuration file provided by “Torch“ with any of the following names:问题解决

问题描述

CMakeLists.txt文件如下:

cmake_minimum_required(VERSION 3.0 FATAL_ERROR)
project(custom_ops)

find_package(Torch REQUIRED)

add_executable(example-app example-app.cpp)
target_link_libraries(example-app "${TORCH_LIBRARIES}")
set_property(TARGET example-app PROPERTY CXX_STANDARD 14)

执行命令报错:

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.cmake

  Add 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.

问题原因

可以看出,就是在第四行,寻找包的时候出错了,没有找到对应的包

只有在cmake中依赖了其他的包,我们才能才在代码中使用#include 而不会出现编译错误

那么需要知道find_package的用法,即寻找依赖包,我的理解是,cmake会默认在系统的安装目录去寻找,如果是通过包管理命令直接安装的包,例如opencv,可能会在/usr/local下,不需要自己添加额外的处理。但是如果是自己下载解压的动态库,或者自己编译源码得到的动态库,就需要进行额外的处理了,具体包括:

  • 如果是下载解压的动态库,那么只需要找到需要的库的.cmake文件即可,这一步需要需要手动指定此文件的目录,让cmake找到它:
export Torch_DIR=/local/xxx/env/lib/python3.8/site-packages/torch/share/cmake

如何得到这个路径呢?
可以执行:

python -c 'import torch;print(torch.utils.cmake_prefix_path)'
  • 如果是自己编译源码得到的动态库,可能要自己写cmake文件?【具体实现方式见参考资料】

问题解决

export Torch_DIR=/local/xxx/env/lib/python3.8/site-packages/torch/share/cmake

参考资料

“轻松搞定CMake”系列之find_package用法详解
Cmake之深入理解find_package()的用法

你可能感兴趣的:(bug,pytorch,人工智能,python)