编译PyTorch转ONNX模型时CMake无法找到ONNX Runtime库求助
编译C++ ONNX推理程序时遇到以下错误:
CMake Error : The following variables are used in this project, but they are set to NOTFOUND. Please set them or make sure they are set and tested correctly in the CMake files : ONNX_RUNTIME_LIB liked by target "ObjectDetectionInferende" in directory /hyeonseop/OD/test/onnx_od
当前使用的CMake代码:
cmake_minimum_required(VERSION 3.25) project(ObjectDetectionInference) find_package(OpenCV REQUIRED) find_path(ONNX_RUNTIME_SESSION_INCLUDE_DIRS onnxruntime_cxx_api.h HINTS "/hyeonseop/OD/onnxruntime-linux-x64-gpu-1.17.0/include") find_library(ONNX_RUNTIME_LIB lib HINTS "/hyeonseop/OD/onnxruntime-linux-x64-gpu-1.17.0") set(SOURCE_FILES main.cpp helper.cpp) add_executable(ObjectDetectionInference ${SOURCE_FILES}) target_include_directories(ObjectDetectionInference PRIVATE ${ONNX_RUNTIME_SESSION_INCLUDE_DIRS}) # ${OpenCV_INCLUDE_DIRS} target_link_libraries(ObjectDetectionInference PRIVATE ${ONNX_RUNTIME_LIB}) # ${OpenCV_LIBRARIES}
ONNX Runtime安装路径为/hyeonseop/OD/onnxruntime-linux-x64-gpu-1.17.0,目录结构:
root@4fe7a1a9f82d:/hyeonseop/OD/onnxruntime-linux-x64-gpu-1.17.0# ls
GIT_COMMIT_ID LICENSE Privacy.md README.md ThirdPartyNotices.txt
VERSION_NUMBER include lib
问题根源
find_library的第二个参数传错了——它需要的是库文件的基础名称,而不是目录名lib。你当前的写法会让CMake去寻找名为lib的库,显然不存在。
修复方案
1. 修正find_library调用
将find_library改为指向lib子目录,并指定正确的库名称:
find_library(ONNX_RUNTIME_LIB NAMES onnxruntime_gpu onnxruntime # 优先匹配GPU版本库 HINTS "/hyeonseop/OD/onnxruntime-linux-x64-gpu-1.17.0/lib")
NAMES后填库的基础名:Linux下库文件是libonnxruntime_gpu.so,CMake会自动补全lib前缀和.so后缀。HINTS直接指向lib子目录,缩小搜索范围。
2. 添加存在性检查(可选但推荐)
在find_path和find_library后添加检查,提前暴露问题:
if(NOT ONNX_RUNTIME_SESSION_INCLUDE_DIRS) message(FATAL_ERROR "未找到ONNX Runtime头文件目录") endif() if(NOT ONNX_RUNTIME_LIB) message(FATAL_ERROR "未找到ONNX Runtime库文件") endif()
3. 恢复OpenCV依赖链接
如果你的代码用到了OpenCV,必须把注释掉的OpenCV依赖恢复:
target_include_directories(ObjectDetectionInference PRIVATE ${ONNX_RUNTIME_SESSION_INCLUDE_DIRS} ${OpenCV_INCLUDE_DIRS}) target_link_libraries(ObjectDetectionInference PRIVATE ${ONNX_RUNTIME_LIB} ${OpenCV_LIBRARIES})
额外说明
- 不需要重新安装ONNX Runtime,路径配置本身没问题,只是CMake调用参数错误。
- 确认
/hyeonseop/OD/onnxruntime-linux-x64-gpu-1.17.0/lib下存在libonnxruntime_gpu.so或libonnxruntime.so文件,若只有带版本号的文件(如libonnxruntime.so.1.17.0),CMake也能自动识别链接。
内容的提问来源于stack exchange,提问作者Hyeonseop Lim

