Search code examples
c++cmakeeigen

config Eigen in CMakeLists.txt file


When I config Eigen library in CMakeLists.txt file as follows:

cmake_minimum_required(VERSION 3.14)
project(helloworld)

add_subdirectory(tests)
add_subdirectory(deps/eigen) 

set(SRC_LIST main.cpp)
add_executable(hello ${SRC_LIST})
find_package(Eigen3 3.3 REQUIRED NO_MODULE)
target_link_libraries(hello eigen)

I got the cmake error as

CMake Error at build/deps/eigen/Eigen3Config.cmake:20 (include):
  The file

    /Users/joe/codecplus/build/deps/eigen/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.

Call Stack (most recent call first):
  CMakeLists.txt:9 (find_package)

Can anybody help me out? Don't know what is going wrong here. Thanks very much.


Solution

  • You use two ways for including 3d-party project (Eigen) at the same time:

    1. add_subdirectory()

    2. find_package()

    This is wrong. Resort to a single way:

    1. With add_subdirectory only:

      add_subdirectory(deps/eigen) 
      # ...
      target_link_libraries(hello Eigen3::eigen)
      
    2. With find_package() only:

      find_package(Eigen3 3.3 REQUIRED NO_MODULE)
      target_link_libraries(hello Eigen3::eigen)
      

    Note, that both approaches uses Eigen3::eigen target instead of eigen for link with. Only this name works with the second approach, and it is described in the documentation for Eigen usage.