LibTorch CMake编译报错:无法找到torch/autograd/profiler.h
解决LibTorch项目引入torch/autograd/profiler.h编译失败问题
问题场景
C++代码:
#include <torch/torch.h> #include <torch/script.h> #include <torch/autograd/profiler.h>
CMakeLists.txt配置:
cmake_minimum_required(VERSION 3.31) project(pytorch_test) set(CMAKE_CXX_STANDARD 20) list(APPEND CMAKE_PREFIX_PATH "/home/research/c++/libtorch/") set(Torch_DIR /home/research/c++/libtorch/) find_package(Torch REQUIRED CONFIG) message(STATUS "Torch_FOUND: ${Torch_FOUND}") add_executable(pytorch_test main.cpp TKEngine/TKEngine.h) target_link_libraries(pytorch_test "${TORCH_LIBRARIES}")
移除#include <torch/autograd/profiler.h>可正常编译,添加后出现错误:
torch/autograd/profiler.h: No such file or directory
解决方法
1. 检查LibTorch安装包完整性
先确认你的LibTorch目录中是否存在目标头文件:
- 查看路径
/home/research/c++/libtorch/include/torch/autograd/profiler.h是否存在 - 如果不存在,说明你下载的是精简版LibTorch,需要重新从PyTorch官网下载完整版本的LibTorch(CPU或CUDA版本均可,避开lite/mini版本)
2. 调整CMake配置确保头文件路径被正确导入
虽然find_package(Torch REQUIRED)会自动处理依赖路径,但可以显式添加头文件目录以确保覆盖:
修改CMakeLists.txt,在target_link_libraries之后添加:
target_include_directories(pytorch_test PRIVATE ${TORCH_INCLUDE_DIRS})
3. 适配不同LibTorch版本的头文件路径
部分LibTorch版本中,profiler头文件路径位于csrc子目录下,尝试修改#include语句为:
#include <torch/csrc/autograd/profiler.h>
4. 验证CMake配置正确性
执行CMake生成构建文件时,查看输出日志中是否包含TORCH_INCLUDE_DIRS的路径,确认其包含了LibTorch的include目录。
内容的提问来源于stack exchange,提问作者Michael zhang
相关产品推荐
相关产品推荐

