Trouble making CMake for using LibTorch with c++

Hi there, I’ve been trying to get set up with LibTorch in c++ using this guide https://pytorch.org/cppdocs/installing.html and been having some troubles.

Context

  • using CUDA 12.1
  • building with cmake tools in vscode

Does anyone have a link to a set up for LibTorch using Cuda?

Thanks

I’m still working on cuda but I got the cpu version working with this cmake (unzipping the libtorch utils into the root of my project):


cmake_minimum_required(VERSION 3.18 FATAL_ERROR)
project(main)

set(CMAKE_PREFIX_PATH "${CMAKE_SOURCE_DIR}/libtorch")

find_package(Torch REQUIRED)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${TORCH_CXX_FLAGS}")

add_executable(main main.cpp)
target_link_libraries(main "${TORCH_LIBRARIES}")
set_property(TARGET main PROPERTY CXX_STANDARD 17)

# The following code block is suggested to be used on Windows.
# According to https://github.com/pytorch/pytorch/issues/25457,
# the DLLs need to be copied to avoid memory errors.
if (MSVC)
  file(GLOB TORCH_DLLS "${CMAKE_SOURCE_DIR}/libtorch/lib/*.dll")
  message("DLL files: ${TORCH_DLLS}")
  add_custom_command(TARGET main
                     POST_BUILD
                     COMMAND ${CMAKE_COMMAND} -E copy_if_different
                     ${TORCH_DLLS}
                     $<TARGET_FILE_DIR:main>
                     )
endif (MSVC)

I then used these commands to build and make it

if exist build rmdir /s /q build
mkdir build
cd build
cmake -G "Visual Studio 17 2022" -T v142 -A x64 ..
cmake --build . --config Debug
Debug\main.exe

My main problems were getting it to use the right compiler since libtorch doesn’t work with the newest visual studio compilers. Here’s versions that worked for me:

To install that specific compiler I used the visual studio installer with the following steps

  • open visual studio installer
  • click ‘modify’ on ‘Visual Studio Build Tools 20XX’
  • go to the ‘Individual components’ tab and search ‘msvc’
  • get an older version of ‘MSVC vXXX - VS 20XX C++ x64/x86 build tools (…)’ that might work with whatever they build libtorch with
  • modify the build command to ‘cmake -G “Visual Studio XX 20XX” -T vXXX -A x64 …’ according to the build tools version you got above