Unique way to enable OpenMP with CMake?

Hi everyone,

I am wondering which is the recommended way to enable OpenMP support, regardless of the OS.

I mostly work on Windows OS, and there it was only “sufficient” to set the target compile options to include the required flag.
I have very recently started to move to UNIX OSes, and there I realised that was not working anymore (failing at link time). So, I went for the find_package route. Solved. But then, this is apparently not working on Windows again, in which CMake is unable to find OpenMP.

This approach is also mentioned here. Here is a similar question, but for MacOS.

So. What is the best (and unique?) way to enable OpenMP support? I would say using the intrinsic module provided FindOpenMP, but I don’t understand why it is not working in this case.

The code:

      find_package( OpenMP )
      if ( NOT OpenMP_Fortran_FOUND )
         message( FATAL_ERROR "OpenMP not found" )
      target_link_libraries( ${project} PUBLIC OpenMP::OpenMP_Fortran )


Yes, doing something like:

find_package(OpenMP REQUIRED)

is the canonical way. Indeed, if you add REQUIRED then there is no need to test if found, CMake will stop at that point if it can’t find OpenMP support.

You then do:

target_link_libraries( target <PUBLIC|PRIVATE> OpenMP::OpenMP_Fortran )

to link to it (CMake will also “pass down” any includes as well this way so you don’t need any target_include_directories).

If you know you only need Fortran you can also do:

find_package(OpenMP REQUIRED COMPONENTS Fortran)

As far as I know, this should be OS agnostic.

1 Like

Thanks @mathomp4 .

Yet, it does not work with

      find_package( OpenMP REQUIRED COMPONENTS Fortran )
      target_link_libraries( ${project} PUBLIC OpenMP::OpenMP_Fortran )

It still fails:

CMake Error at C:/Program Files/CMake/share/cmake-3.29/Modules/FindPackageHandleStandardArgs.cmake:230 (message):
  Could NOT find OpenMP_Fortran (missing: OpenMP_Fortran_FLAGS
Call Stack (most recent call first):
  C:/Program Files/CMake/share/cmake-3.29/Modules/FindPackageHandleStandardArgs.cmake:600 (_FPHSA_FAILURE_MESSAGE)
  C:/Program Files/CMake/share/cmake-3.29/Modules/FindOpenMP.cmake:581 (find_package_handle_standard_args)
  src/CMakeLists.txt:123 (find_package)

Hmm. I guess next question: what is your Fortran compiler? Maybe it’s a compiler CMake does not know about?

I think if you know the exact flag used by the Fortran compiler, you can specify it with:

cmake -DOpenMP_Fortran_FLAG="-flag" ...

Mh, I doubt, since it is the ifort Intel compiler. On UNIX it works, while it crashes on Windows.
The same using the new ifx compiler.

Well then, looking at Gitlab and seeing this:


I think it’s time to mention @brad.king

Maybe it’s possible you have just a perfectly wrong version of CMake 3.29?