Skip to content

Instantly share code, notes, and snippets.

@hugmanrique
Last active September 4, 2022 02:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hugmanrique/4135846fb2995024721e65e1013c6b46 to your computer and use it in GitHub Desktop.
Save hugmanrique/4135846fb2995024721e65e1013c6b46 to your computer and use it in GitHub Desktop.
How to install and interface with LAPACK from a C++ project

Installation

To install BLAS and LAPACK on a Debian-based system, run

$ sudo apt install libblas-dev liblapack-dev

The LAPACKE library provides a C interface to LAPACK, and can be installed using

$ sudo apt install liblapacke-dev

The Intel Math Kernel Library provides additional optimized routines. It supports AMD CPUs, yet its performance is not guaranteed. The package resides on Debian's non-free archive area and can be installed using

sudo apt install intel-mkl
export MKL_DEBUG_CPU_TYPE=5 # (Only on AMD CPUs) Enable high performance mode, unsupported.

Usage

To link against the BLAS and LAPACK libraries, add the following to the CMakeLists.txt file:

find_package(BLAS REQUIRED)
find_package(LAPACK COMPONENTS Netlib LAPACKE REQUIRED)

# After the target definitions (e.g. add_executable)
target_link_libraries(the_project_name lapacke ${LAPACK_LIBRARIES} ${BLAS_LIBRARIES} m)

To ensure everything went correctly, compile and execute the following toy program that prints the eigenvalues of the matrix $A = \begin{bmatrix}1 & 4 & 7\\2 & 5 & 8\\3 & 6 & 9\end{bmatrix}$:

#include <cassert>
#include <iostream>
#include <lapacke.h>

int main() {
    constexpr int N = 3;
    double mat[N * N] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
    double eigval_real[N], eigval_imag[N];
    assert(!(LAPACKE_dgeev(LAPACK_COL_MAJOR, 'N', 'N', N, &mat[0], N, &eigval_real[0], &eigval_imag[0], nullptr, 1, nullptr, 1)));
    for (int i = 0; i < N; ++i)
        std::cout << eigval_real[i] << "+" << eigval_imag[i] << "i\n";
    return 0;
}

Note that $\operatorname{Spec}(A) \approx \{16.1168, -1.1168, 0\}$. To use the BLAS routines, include the cblas.h header file.

Intel provides a guide on how to integrate the MKL library into a CMake project (archive).

References

To install the BLAS and LAPACK manual, execute

$ sudo apt install liblapack-doc

You can now navigate the manpages for all the routines, e.g. man dgeev.

Some helpful resources include

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment