Search code examples
c++cmakeeigen

cmake Eigen find_package HINTS


I need to add Eigen to one of our projects. Since Eigen is header-only we decided to put it directly into our source-code directory to track it with Git and make sure that everything is ready as soon as you clone the repository. Therefore, we downloaded Eigen from here and placed it in the directory EIGEN inside our project directory.

We are using cmake in this project. I can include Eigen using the following code:

find_package(Eigen3 REQUIRED)
if (Eigen3_FOUND)
    message("Eigen found")
    message("  Eigen location: ${Eigen3_DIR}")
    message("  Eigen Version: ${Eigen3_VERSION}")
    target_link_libraries (ourProject Eigen3::Eigen)
endif ()

However, this code does find a different Eigen version located in /usr/local/share/eigen3/cmake.

I want it to use the Eigen version located in the source-code directory. Therefore, I tried to use the HINTS option:

find_package(Eigen3 REQUIRED HINTS ./EIGEN)

but it does not work. My main problem is that I do not know which path I have to write into the HINTS. The EIGEN directory contains multiple other folders. I tried some of them but with no luck:

find_package(Eigen3 REQUIRED HINTS ./EIGEN/Eigen)
find_package(Eigen3 REQUIRED HINTS ./EIGEN/Eigen/src)
find_package(Eigen3 REQUIRED HINTS ./EIGEN/cmake)...

What is the correct way to make ensure that cmake does use the Eigen version I want?


Solution

  • Like squareskittles mentioned in the comments, you should call add_subdirectory() with the location of Eigen3 in your source tree. You then won't need to call find_package(), as long as you are only using the Eigen3::Eigen target as this will be added by the Eigen3 CMake scripts.

    So if you had the following source tree:

    - foo/
      - CMakeLists.txt    # Top-level CMakeLists file
      - eigen/            # Cloned Eigen repo
        - CMakeLists.txt
        - ...
      - foo.cpp
      - foo.hpp
    

    Your foo/CMakeLists.txt should contain:

    add_subdirectory(eigen)
    

    Be wary though, some CMake variables may not be set without calling find_package() - Eigen3_VERSION and Eigen3_INCLUDE_DIR for example. If you do decide to call find_package() to get these, you don't need to give it a HINTS parameter, and can provide CONFIG or NO_MODULE to go straight into Config mode.

    Then CMake will search for an Eigen3Config.cmake instead of a FindEigen3.cmake, which will be generated in the Eigen build tree.