Detecting the OpenMP parallel environment

The code for this recipe is available at https://github.com/dev-cafe/cmake-cookbook/tree/v1.0/chapter-03/recipe-05 and has a C++ and Fortran example. The recipe is valid with CMake version 3.9 (and higher) and has been tested on GNU/Linux, macOS, and Windows. In  https://github.com/dev-cafe/cmake-cookbook/tree/v1.0/chapter-03/recipe-05, we also provide examples compatible with CMake 3.5.

Today, basically any computer on the market is a multi-core machine and for programs focusing on performance, we may have to focus on these multi-core CPUs and use concurrency in our programming models. OpenMP is the standard for shared-memory parallelism on multi-core CPUs. Existing programs often do not need to be radically modified or rewritten in order to benefit from OpenMP parallelization. Once the performance-critical sections in the code are identified, for example using a profiling tool, the programmer can add preprocessor directives that will instruct the compiler to generate parallel code for those regions.

In this recipe, we will show how to compile a program containing OpenMP directives, provided we use an OpenMP-aware compiler. Many Fortran, C, and C++ compilers exist that can take advantage of OpenMP parallelism. CMake provides very good support for OpenMP in combination with C, C++, or Fortran for relatively recent versions of CMake. This recipe will show you how to detect and link to OpenMP using imported targets for simple C++ and Fortran programs when using CMake 3.9 or above.

Depending on the Linux distribution, the Clang compiler may not have OpenMP support in its default version. This recipe will not work on macOS unless a separate libomp installation ( https://iscinumpy.gitlab.io/post/omp-on-high-sierra/) or a non-Apple version of Clang (e.g., provided by Conda) or the GNU compilers are used.