How to set linker flags for OpenMP in CMake's try_compile function

Solution 1:

CMake has a standard module for testing if the compiler supports OpenMP:

find_package(OpenMP)
if (OPENMP_FOUND)
    set (CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${OpenMP_C_FLAGS}")
    set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${OpenMP_CXX_FLAGS}")
    set (CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${OpenMP_EXE_LINKER_FLAGS}")
endif()

Note:
This answer is not recommended to be used anymore for including OpenMP in the project for current CMake versions. Refer to the other answers.

Solution 2:

As of CMake 3.9 there are imported OpenMP targets per language. I consider this to be a much more elegant solution. Here's an example in C++:

cmake_minimum_required(VERSION 3.9)
project(solver LANGUAGES CXX)

find_package(OpenMP REQUIRED)
add_executable(solver solver.cc)
target_link_libraries(solver PRIVATE OpenMP::OpenMP_CXX)

This is more convenient since it is less typing, and this way you don't have to adjust with compile flags, libraries, etc which are error-prone. This is the direction that modern CMake is going.


If you are working with something older than CMake 3.9 I still don't recommend the currently accepted answer. I believe setting the flags per-target is better:

add_executable(solver solver.cc)
target_link_libraries(solver PRIVATE "${OpenMP_CXX_FLAGS}")
target_compile_options(solver PRIVATE "${OpenMP_CXX_FLAGS}")

This may not work with some compilers; this is partly why CMake revamped its OpenMP support in CMake 3.9.

Solution 3:

OpenMP support has been improved in CMake 3.9+

CMakeLists.txt

cmake_minimum_required(VERSION 3.9)
project(openmp_test) # you can change the project name

find_package(OpenMP)

add_executable(openmp_para_test main.cpp) # you can change the excutable name

if(OpenMP_CXX_FOUND)
    target_link_libraries(openmp_para_test PUBLIC OpenMP::OpenMP_CXX)
endif()

This way will correctly set the library link line differently from the compile line if needed.

Source.

Solution 4:

In case you try to use the "modern" way with g++, you could also do:

find_package(OpenMP REQUIRED)

add_executable(Foo foo.cpp)
target_compile_options(Foo PRIVATE -Wall ${OpenMP_CXX_FLAGS})
target_link_libraries(Foo PRIVATE ${OpenMP_CXX_FLAGS})

Notice:

  1. If you would leave out only the target_compile_options your pragmas would simple be ignored (enabled warnings would tell you)

  2. If you would leave out only the target_link_libraries your code wouldn't compile, as g++ is not properly linked

  3. If you leave both out the 1. note applies rendering the linking no longer needed and your code would compile.

I don't know whether this linking "hack" with the flags is working for other compilers as well.