Run an example C/C++ program

The mpihello.c program is a 'Hello World' example C MPI program:

// mpihello.c
#include <stdio.h>
#include <stddef.h>
#include <mpi.h>

int main()
{
int rank, size;

MPI_Init(NULL, NULL);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
printf("Hello World, rank: %5d size: %5d\n", rank, size);
MPI_Finalize();
return 0;
}

The program comprises four common Open MPI functions:

  • MPI_Init
  • MPI_Comm_Rank
  • MPI_Comm_Size
  • MPI_Finalize

To run this program with the library build:

  1. Compile the mpihello.c program:

    mpicc -O3 -o mpihello mpihello.c
    
  2. Execute the mpihello program:

    mpiexec -np 4 ./mpihello

    to return:

     Hello World, rank:     0 size:     4
     Hello World, rank:     2 size:     4
     Hello World, rank:     1 size:     4
     Hello World, rank:     3 size:     4

    Note: The ordering of the output may change due to parallelism.

Previous Next