c++cmakeeigen3

How to add Eigen library to a cmake c++ project via FetchContent


Adding Eigen via

FetchContent_Declare(
  eigen
  GIT_REPOSITORY https://gitlab.com/libeigen/eigen.git
  GIT_TAG        3.3.9
)

FetchContent_GetProperties(eigen)

if(NOT eigen_POPULATED)
    FetchContent_Populate(eigen)
    add_subdirectory(${eigen_SOURCE_DIR} ${eigen_BINARY_DIR})
endif()

find_package (Eigen3 3.3 REQUIRED NO_MODULE) 

gives me the error

CMake Error at o/b/x64-Debug/_deps/eigen-build/Eigen3Config.cmake:20 (include):
  The file

    D:/XXX/o/b/x64-Debug/_deps/eigen-build/Eigen3Targets.cmake

  was generated by the export() command.  It may not be used as the argument
  to the include() command.  Use ALIAS targets instead to refer to targets by
  alternative names.        D:\XXX\o/b/x64-Debug/_deps/eigen-build/Eigen3Config.cmake   20

But downloading Eigen manually and adding it works fine

add_subdirectory("${PROJECT_SOURCE_DIR}/extern/eigen")
find_package (Eigen3 3.3 REQUIRED NO_MODULE) 

Any ideas ?


Solution

  • In any order:

    message(CHECK_START "Fetching Eigen3")
    list(APPEND CMAKE_MESSAGE_INDENT "  ")
    
    include(FetchContent)
    FetchContent_Declare(
      Eigen
      GIT_REPOSITORY https://gitlab.com/libeigen/eigen.git
      GIT_TAG master
      GIT_SHALLOW TRUE
      GIT_PROGRESS TRUE)
    # note: To disable eigen tests,
    # you should put this code in a add_subdirectory to avoid to change
    # BUILD_TESTING for your own project too since variables are directory
    # scoped
    set(BUILD_TESTING OFF)
    set(EIGEN_BUILD_TESTING OFF)
    set(EIGEN_MPL2_ONLY ON)
    set(EIGEN_BUILD_PKGCONFIG OFF)
    set(EIGEN_BUILD_DOC OFF)
    FetchContent_MakeAvailable(Eigen)
    
    list(POP_BACK CMAKE_MESSAGE_INDENT)
    message(CHECK_PASS "fetched")
    ...
    target_link_libraries(YourTarget PRIVATE Eigen3::Eigen)