Compile libtorch with g++

Hi all,

I was trying to add the libtorch library to my C++ project which is being built by using g++. I tried to include the specified files in the g++ command but it does not seem to work. I follow the example-app from

My command that was used to compile the c++ source code is:
(I added /path/to/libtorch/lib/ to LD_LIBRARY_PATH in ~/.bashrc)

$ g++ -std=gnu++11 -o test *.cpp \
-I /path/to/libtorch/include/torch/csrc/api/include/ \
-I /path/to/libtorch/include/ \
-L /path/to/libtorch/lib/ \
-lc10 \
-lCaffe2_perfkernels_avx512 -lCaffe2_perfkernels_avx2 -lCaffe2_perfkernels_avx \
-lnnpack -lpytorch_qnnpack -lqnnpack -lXNNPACK \
-lcaffe2_protos -lprotobuf-lite -lprotobuf -lprotoc \
-lonnx -lonnx_proto -lfoxi_loader -lfmt -lclog -lcpuinfo \
-lpthreadpool -lfbgemm -ldnnl -lmkldnn -lasmjit

I got the following error message:

/tmp/cchwVWtY.o: In function `at::operator<<(std::ostream&, at::Tensor const&)':
main.cpp:(.text+0x13c): undefined reference to `at::print(std::ostream&, at::Tensor const&, long)'
/tmp/cchwVWtY.o: In function `torch::autograd::AutogradMeta::AutogradMeta(c10::TensorImpl*, bool, torch::autograd::Edge)':
main.cpp:(.text._ZN5torch8autograd12AutogradMetaC2EPN3c1010TensorImplEbNS0_4EdgeE[_ZN5torch8autograd12AutogradMetaC5EPN3c1010TensorImplEbNS0_4EdgeE]+0x38): undefined reference to `vtable for torch::autograd::AutogradMeta'
/tmp/cchwVWtY.o: In function `torch::rand(c10::ArrayRef<long>, c10::TensorOptions)':
main.cpp:(.text._ZN5torch4randEN3c108ArrayRefIlEENS0_13TensorOptionsE[_ZN5torch4randEN3c108ArrayRefIlEENS0_13TensorOptionsE]+0x96): undefined reference to `at::rand(c10::ArrayRef<long>, c10::TensorOptions)'
collect2: error: ld returned 1 exit status

I also tried to compile with -std=gnu++11 but it does not work.

I also tried the suggested solution that was mentioned by [pim] & [thekchang] at this thread

The compilation of the example-app with Cmake as describe worked great. However, it will be more convenient and save more time to compile and debug my project with g++ rather than Cmake. So my question “How can we use libtorch with the compilation with a normal compiler (e.g., g++) on terminal”

Thank you for your time and your effort. Any help would be greatly appreciated !!

Hi, I also faced similar build error info. I built the libtorch from source with MKL, MKLDNN(oneDNN), MAGMA and CUDA. The generated libs file include, You need link them: “-ltorch -ltorch_cpu -lc10 …”