Search code examples
c++cmakeeigen

Eigen library setup in CMakeLists.txt


I have a project file structure like this:

.
├── CMakeLists.txt
├── deps
│   ├── cxxtest
│   └── eigen
├── main.cpp
└── tests
    ├── CMakeLists.txt
    └── hello_world.cpp

and the two CMakeLists.txt files and two .cpp files are

enter image description here

So my question is why I have to put the Eigen library setup in the top level of CMakeLists.txt file as follow to make the top level .cpp file work, i.e., finding the Eigen/Dense header, but the lower level of .cpp will always work no matter if both the top and the lower levels of CMakeLists.txt files have the following setup or not?

find_package(Eigen3 3.3 REQUIRED NO_MODULE)
target_link_libraries(proj Eigen3::Eigen)

Solution

  • I guess you want to use the local Eigen library in your project directory tree, i.e. deps/eigen. The easiest way to do this is to just add the Eigen subdirectory as normal, using add_subdirectory. You also might need to change the target library from Eigen3::Eigen to eigen. The main CMakeLists.txt then looks like this:

    cmake_minimum_required(VERSION 3.14)
    project(PROJECT)
    
    add_subdirectory(deps/eigen)
    add_subdirectory(tests)
    
    set(SRC_LIST main.cpp)
    add_executable(proj ${SRC_LIST})
    target_link_libraries(proj eigen)
    

    Also, in order to make the unit test hello_world.cpp work you need to add the linking to the Eigen library in the CMakeLists.txt in the tests directory, i.e.:

    target_link_libraries(hello_world eigen)