How to do it

In this recipe, we set out to find the MPI implementation: library, header files, compiler wrappers, and launcher. To do so, we will leverage the FindMPI.cmake standard CMake module:

  1. First, we define the minimum CMake version, project name, supported language, and language standard:
cmake_minimum_required(VERSION 3.9 FATAL_ERROR)

project(recipe-06 LANGUAGES CXX)

set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_EXTENSIONS OFF)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
  1. We then call find_package to locate the MPI implementation:
find_package(MPI REQUIRED)
  1. We define the executable name and, source, and similarly to the previous recipe, link against the imported target:
add_executable(hello-mpi hello-mpi.cpp)

target_link_libraries(hello-mpi
PUBLIC
MPI::MPI_CXX
)
  1. Let us configure and build the executable:
$ mkdir -p build
$ cd build
$ cmake -D CMAKE_CXX_COMPILER=mpicxx ..

-- ...
-- Found MPI_CXX: /usr/lib/openmpi/libmpi_cxx.so (found version "3.1")
-- Found MPI: TRUE (found version "3.1")
-- ...

$ cmake --build .
  1. To execute this program in parallel, we use the mpirun launcher (in this case, using two tasks):
$ mpirun -np 2 ./hello-mpi

Hello world from processor larry, rank 1 out of 2 processors
Hello world from processor larry, rank 0 out of 2 processors