CMake: creating a serial and parallel (MPI) build for a project

Viewed 102

I would like to create a parallel build of my project along with the serial executable. The sources (both added libraries and main.cpp) use a define to enable MPI. When the serial version is compiled, the define is not present however I need to recompile everything with the define to create the parallel executable.

Is it possible to get CMake to compile the serial executable, then recompile everything with an additional add_compile_definitions (as well as linking MPI_C) so that the MPI code is enabled and a parallel executable is created?

1 Answers

Just create two different executable targets with the same list of sources and use target_compile_definitions and target_link_libraries on each one...

cmake_minimum_required(VERSION 3.21)
project(mpi-example LANGUAGES C)

find_package(MPI REQUIRED)

set(sources src/main.c src/foo.c ...)

# Serial version of the code
add_executable(app_serial ${sources})

# MPI version of the code
add_executable(app_mpi ${sources})
target_compile_definitions(app_mpi PRIVATE WITH_MPI)
target_link_libraries(app_mpi PRIVATE MPI::MPI_C)
Related