Search code examples
cmakeblasopenblas

Use cmake FindBLAS to link OpenBLAS


I am using cmake 3.16, and I know that cmake supports finding OpenBLAS by using FindBLAS (here).

I am trying to link OpenBLAS to my c++ project. Here is my CMakeLists.txt.

cmake_minimum_required(VERSION 3.15)

project(my_project)

# source file
file(GLOB SOURCES "src/*.cpp")

# executable file
add_executable(main.exe ${SOURCES})

# link openblas
set(BLA_VENDER OpenBLAS)
find_package(BLAS REQUIRED)
if(BLAS_FOUND)
    message("OpenBLAS found.")
    include_directories(${BLAS_INCLUDE_DIRS})
    target_link_libraries(main.exe ${BLAS_LIBRARIES})
endif(BLAS_FOUND)

If I run cmake, it runs just find, and outputs OpenBLAS found.. However, if I start to compile the codes (make VERBOSE=1), the library is not linked, so that the codes fail to compile. Here is the error info:

fatal error: cblas.h: No such file or directory
 #include <cblas.h>
          ^~~~~~~~~
compilation terminated.

I installed OpenBLAS successfully. The header files are in /opt/OpenBLAS/include, and the shared libraries are in /opt/OpenBLAS/lib. My OS is ubuntu 18.04.

Any help? Thank you!


Solution

  • Thanks Tsyvarev. I found the problem.

    I tried to use message() to print out the variables.

    message(${BLAS_LIBRARIES})
    

    Which gives:

    /opt/OpenBLAS/lib/libopenblas.so
    

    So the shared library is found.

    However, for BLAS_INCLUDE_DIRS, it gives:

    message(${BLAS_INCLUDE_DIRS})
    CMake Error at CMakeLists.txt:27 (message):
      message called with incorrect number of arguments
    

    It turns out that BLAS_INCLUDE_DIRS is not in the FindBLAS variables. So I add the include header files manually:

    set(BLA_VENDER OpenBLAS)
    find_package(BLAS REQUIRED)
    if(BLAS_FOUND)
        message("OpenBLAS found.")
        include_directories(/opt/OpenBLAS/include/)
        target_link_libraries(main.exe ${BLAS_LIBRARIES})
    endif(BLAS_FOUND)
    

    This time it compiles without error. Instead of using include_directories(), you could also try find_path() (check this).