首先,下载Libtorch:https://pytorch.org/get-started/locally/
然后打开你的项目,使用CMake
构建哦w
例如我的:
cmake_minimum_required(VERSION 3.15)
project(TorchFly)
set(CMAKE_CXX_STANDARD 14)
set(Torch_DIR ~/SDK/libtorch/share/cmake/Torch)
find_package(Torch REQUIRED)
add_executable(TorchFly src/main.cpp)
target_link_libraries(TorchFly ${TORCH_LIBRARIES})
其中 set(Torch_DIR ~/SDK/libtorch/share/cmake/Torch)
就是你的Torch的路径,绝对路径与相对路径都可以。add_executable(TorchFly src/main.cpp)
是什么不多说了(((
然后是CPP文件:
#include <torch/torch.h>
#include <iostream>
int main() {
torch::Tensor tensor = torch::eye(4);
std::cout << tensor << std::endl;
}
好了,运行就会输出:
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1
[ Variable[CPUFloatType]{4,4} ]
如果出现:
dyld: Library not loaded: @rpath/libmklml.dylib
Referenced from: ~/libtorch/lib/libtorch.dylib
Reason: image not found
下载:https://github.com/intel/mkl-dnn/releases 中对于你的系统的版本,解压后把lib文件夹的 .dylib
文件拷贝到 libtorch/lib/
里。