Pytorch environment to build C++

1. Read the Pytorch C++ official website document , install the Linux operating system of Ubuntu16.04 on the virtual machine to build the environment, and use the makefile to compile, the code is concise and easy to read.

sudo apt-get update 
sudo apt-get install vim make cmake gcc g++ libnss3 tree git openssh-server openssh-client

2. Download the pytorch c++ cpu library file , and unzip it, pay attention to the directory path, cmake compilation needs

unzip libtorch-shared-with-deps-latest.zip
pwd

3. Install vscode, download link: linux vscode , unzip and start

sudo dpkg -i code_1.32.1-1552006243_amd64.deb
code

4. Create a project, directory structure:

ai@ai-virtual-machine:~/pro/tb/day01_test_env_cpu$ tree
.
├── bin                # cmake 编译输出的文件目录
├── CMakeLists.txt     # cmake文件
├── main.cpp           # 主程序
└── makefile           # make编译CMakeLists.txt,代码简洁

main.cpp, code

#include <torch/script.h>
#include <ATen/ATen.h>

#include <iostream>

using namespace std;
using namespace at;

int main(int argc, const char* argv[])
{
    at::Tensor a = at::ones({2,2}, at::kInt);
    std::cout << a << std::endl;

    std::cout << "ok" << std::endl;
    return 0;
}

CMakeLists.txt, code

cmake_minimum_required(VERSION 3.0 FATAL_ERROR)
     

project(demo)

find_package(Torch REQUIRED)
     
add_executable(${PROJECT_NAME} main.cpp)

target_link_libraries(${PROJECT_NAME} "${TORCH_LIBRARIES}")

set_property(TARGET ${PROJECT_NAME} PROPERTY CXX_STANDARD 11)

makefile, code

.PHONY:all clean
     
PATH_BIN=bin


pytorch_lib=/home/ai/pro/tb/libtorch
     

all:

	@cd ./$(PATH_BIN) && cmake -DCMAKE_PREFIX_PATH=$(pytorch_lib) .. && make
     

clean:

	rm -rf $(PATH_BIN)

	mkdir $(PATH_BIN)

Compile, make

运 运, ./bin/demo

Engineering code download link: https://download.csdn.net/download/wzhrsh/13206964

 

Guess you like

Origin blog.csdn.net/wzhrsh/article/details/110388086