CMake Cookbook
上QQ阅读APP看书,第一时间看更新

How to do it

Our CMakeLists.txt for the C++ and Fortran examples will follow a template that is largely similar between the two languages:

  1. Both define a minimum CMake version, project name, and language (CXX or Fortran; we will show the C++ version):
cmake_minimum_required(VERSION 3.9 FATAL_ERROR)

project(recipe-05 LANGUAGES CXX)
  1. For the C++ example, we require the C++11 standard:
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_EXTENSIONS OFF)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
  1. Both call find_package to search for OpenMP:
find_package(OpenMP REQUIRED)
  1. Finally, we define the executable target and link to the imported target provided by the FindOpenMP module (in the Fortran case, we link against OpenMP::OpenMP_Fortran):
add_executable(example example.cpp)

target_link_libraries(example
PUBLIC
OpenMP::OpenMP_CXX
)
  1. Now, we can configure and build the code:
$ mkdir -p build
$ cd build
$ cmake ..
$ cmake --build .
  1. Let us first test it out in parallel (in this example using four cores):
$ ./example 1000000000

number of available processors: 4
number of threads: 4
we will form sum of numbers from 1 to 1000000000
sum: 500000000500000000
elapsed wall clock time: 1.08343 seconds
  1. For comparison, we can rerun the example with the number of OpenMP threads set to 1:
$ env OMP_NUM_THREADS=1 ./example 1000000000

number of available processors: 4
number of threads: 1
we will form sum of numbers from 1 to 1000000000
sum: 500000000500000000
elapsed wall clock time: 2.96427 seconds