Wei Zhang's Blog

03 Feb 2022

Makefile for applications based on LibTorch C++ API

Code using LibTorch C++ APIs can be compiled using CMake, as suggested in this page. Alternatively, one can compile the code by writing a simple makefile. As an example, to compile the following C++ source code

example.cpp

#include <torch/torch.h>
#include <iostream>

int main() {
  torch::Tensor tensor = torch::rand({2, 3});
  std::cout << tensor << std::endl;
}

we can use the makefile as below.

# Location to the LibTorch library
LIBTORCH = /home/wei/miniconda3/envs/base/libtorch
LDFLAGS = -Wl,-rpath,${LIBTORCH}/lib -L${LIBTORCH}/lib
CXXFLAGS = -std=c++14 -D_GLIBCXX_USE_CXX11_ABI=1
LIBS = -ltorch -ltorch_cpu -lc10 -ltorch
CPPFLAGS = -I${LIBTORCH}/include -I${LIBTORCH}/include/torch/csrc/api/include

CC = g++

example: example.o
	${CC}  $< -o $@ ${LDFLAGS} ${LIBS}

example.o: example.cpp
	${CC} ${CPPFLAGS} ${CXXFLAGS} -c $<

clean: 
	rm -f example example.o

Tags