【pytorch】libtorch的CMake问题
(1)单一文件
即将源文件和CMakeLists.txt放在同一文件夹下,那么:
cmake_minimum_required(VERSION 3.0 FATAL_ERROR)
project(test1)
set(Torch_DIR "/your/path/libtorch/share/cmake/Torch")
find_package(Torch REQUIRED)
add_executable(test1 test1.cpp)
target_link_libraries(test1 "${TORCH_LIBRARIES}")
set_property(TARGET test1 PROPERTY CXX_STANDARD 14)
此处使用的是Pre-cxx11 ABI
(2)分文件编写项目
文件结构如下:
.
├── CMakeLists.txt
├── include
│ └── test.h
├── src
│ └── test.cpp
└── test_m.cpp
编写CMakeList.txt
cmake_minimum_required(VERSION 3.0 FATAL_ERROR)
project(test1)
set(Torch_DIR "/your/path/libtorch/share/cmake/Torch")
find_package(Torch REQUIRED)
find_package(OpenCV REQUIRED)
include_directories(
${PROJECT_SOURCE_DIR}
${PROJECT_SOURCE_DIR}/include
)
add_library(${PROJECT_NAME} SHARED
src/test.cpp
include/test.h
)
add_executable(test_m test_m.cpp)
target_link_libraries(test_m
${PROJECT_NAME}
${TORCH_LIBRARIES}
)
set_property(TARGET test_m PROPERTY CXX_STANDARD 14)
报错:
fatal error: torch/torch.h: 没有那个文件或目录 #include <torch/torch.h>
修改:
include_directories(
${PROJECT_SOURCE_DIR}
${PROJECT_SOURCE_DIR}/include
${TORCH_INCLUDE_DIRS}
)
报错:
CMakeFiles/test_m.dir/test_m.cpp.o:在函数‘c10::IValue::isIntrusivePtr() const’中:
test_m.cpp:(.text._ZNK3c106IValue14isIntrusivePtrEv[_ZNK3c106IValue14isIntrusivePtrEv]+0x17b):对‘c10::detail::torchInternalAssertFail(char const*, char const*, unsigned int, char const*, std::string const&)’未定义的引用
CMakeFiles/test_m.dir/test_m.cpp.o:在函数‘c10::IValue::toComplexDouble() const’中:
test_m.cpp:(.text._ZNK3c106IValue15toComplexDoubleEv[_ZNK3c106IValue15toComplexDoubleEv]+0x88):对‘c10::detail::torchInternalAssertFail(char const*, char const*, unsigned int, char const*, std::string const&)’未定义的引用
collect2: error: ld returned 1 exit status
CMakeFiles/test_m.dir/build.make:101: recipe for target 'test_m' failed
make[2]: *** [test_m] Error 1
CMakeFiles/Makefile2:110: recipe for target 'CMakeFiles/test_m.dir/all' failed
make[1]: *** [CMakeFiles/test_m.dir/all] Error 2
Makefile:90: recipe for target 'all' failed
make: *** [all] Error 2
这个原因不知道为什么,猜想是因为使用的包是Pre-cxx11 ABI,因为更换为cxx11 ABI包,便可以正常编译执行了。