- CMake Cookbook
- Radovan Bast Roberto Di Remigio
- 384字
- 2025-04-04 16:17:18
How to do it
In this project, we will find the Eigen and BLAS libraries, as well as OpenMP, and instruct Eigen to use OpenMP parallelization and to offload part of the linear algebra work to the BLAS library:
- We first declare the minimum CMake version, project name, and use of the C++11 language:
cmake_minimum_required(VERSION 3.9 FATAL_ERROR)
project(recipe-07 LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_EXTENSIONS OFF)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
- We also ask for OpenMP, since Eigen can make use of shared-memory parallelism for dense operations:
find_package(OpenMP REQUIRED)
- We search for Eigen by calling find_package in CONFIG mode (we will discuss this in the next section):
find_package(Eigen3 3.3 REQUIRED CONFIG)
- If Eigen was found, we print out a helpful status message. Notice that we are using the Eigen3::Eigen target. As we have learnt in the previous two recipes, this is an IMPORTED target, offered by the native CMake scripts distributed with Eigen:
if(TARGET Eigen3::Eigen)
message(STATUS "Eigen3 v${EIGEN3_VERSION_STRING} found in ${EIGEN3_INCLUDE_DIR}")
endif()
- Next, we declare an executable target for our source file:
add_executable(linear-algebra linear-algebra.cpp)
- We then find BLAS. Notice that the dependency is now not required:
find_package(BLAS)
- If BLAS is found, we set the corresponding compile definition and link libraries for the executable target:
if(BLAS_FOUND)
message(STATUS "Eigen will use some subroutines from BLAS.")
message(STATUS "See: http://eigen.tuxfamily.org/dox-devel/TopicUsingBlasLapack.html")
target_compile_definitions(linear-algebra
PRIVATE
EIGEN_USE_BLAS
)
target_link_libraries(linear-algebra
PUBLIC
${BLAS_LIBRARIES}
)
else()
message(STATUS "BLAS not found. Using Eigen own functions")
endif()
- Finally, we link to the imported Eigen3::Eigen and OpenMP::OpenMP_CXX targets. This is enough to set all the necessary compile and link flags:
target_link_libraries(linear-algebra
PUBLIC
Eigen3::Eigen
OpenMP::OpenMP_CXX
)
- We are now ready to configure the project:
$ mkdir -p build
$ cd build
$ cmake ..
-- ...
-- Found OpenMP_CXX: -fopenmp (found version "4.5")
-- Found OpenMP: TRUE (found version "4.5")
-- Eigen3 v3.3.4 found in /usr/include/eigen3
-- ...
-- Found BLAS: /usr/lib/libblas.so
-- Eigen will use some subroutines from BLAS.
-- See: http://eigen.tuxfamily.org/dox-devel/TopicUsingBlasLapack.html
- Finally, we compile and test the code. Observe that the binary uses, in this case, four available threads:
$ cmake --build .
$ ./linear-algebra 1000
Number of threads used by Eigen: 4
matrices allocated and initialized Sun Jun 17 2018 11:04:20 AM
elapsed time: 0.0492328s
Scaling done, A and b saved Sun Jun 17 2018 11:04:20 AM
elapsed time: 0.0492328s
Linear system solver done Sun Jun 17 2018 11:04:20 AM
elapsed time: 0.483142s
relative error is 4.21946e-13