0

I am trying to use FetchContent_Declare in order to download the libtorch library, avoiding manual setup. In order to achieve this, I am using the following CMakeLists.txt file:

cmake_minimum_required(VERSION 3.14 FATAL_ERROR)

# Set the project name and version
project(foo VERSION 1.0)

# Set the C++ standard
set(CMAKE_CXX_STANDARD 14)
set(CMAKE_CXX_STANDARD_REQUIRED True)

# ADD LibTorch
FetchContent_Declare(
  LibTorch
  URL https://download.pytorch.org/libtorch/cpu/libtorch-win-shared-with-deps-debug-2.0.0%2Bcpu.zip
)

FetchContent_GetProperties(LibTorch)
if(NOT LibTorch_POPULATED)
  FetchContent_Populate(LibTorch)
  set(Torch_DIR ${LibTorch_SOURCE_DIR}/share/cmake/Torch)
  set(CMAKE_PREFIX_PATH ${LibTorch_SOURCE_DIR})
endif()

message("LibTorch_SOURCE_DIR=${LibTorch_SOURCE_DIR}")
message("Torch_DIR=${Torch_DIR}")
message("CMAKE_PREFIX_PATH=${CMAKE_PREFIX_PATH}")

# Find the PyTorch package
find_package(Torch REQUIRED)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${TORCH_CXX_FLAGS}")

# Add the main executable
add_executable(foo "main.cpp")

# Link the PyTorch libraries
target_link_libraries(foo "${TORCH_LIBRARIES}")

# 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 "${TORCH_INSTALL_PREFIX}/lib/*.dll")
  add_custom_command(TARGET foo
                     POST_BUILD
                     COMMAND ${CMAKE_COMMAND} -E copy_if_different
                     ${TORCH_DLLS}
                     $<TARGET_FILE_DIR:foo>)
endif (MSVC)

# Set the output directory
set_target_properties(foo PROPERTIES
  RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin"
)

However, this results in CMake not being able to find the TorchConfig.cmake file, resulting in an error. In fact, the variables LibTorch_SOURCE_DIR and CMAKE_PREFIX_PATH are indeed empty. The variable Torch_DIR contains /share/cmake/Torch, which is wrong, given that I am on Windows 11 (using Visual Studio).

What am I doing wrong?

0RI0N
  • 33
  • 5
  • `find_package` works with **already installed** packages. It doesn't work with the package which is currently configured (via FetchContent). – Tsyvarev Apr 11 '23 at 21:36

0 Answers0