Travv92
Travv92

Reputation: 801

MPI creating structs over functions in C?

I'm creating a struct to send over MPI but am having a little trouble with using the struct in other functions..

typedef struct Coordinates
{
    int x;
    int y;
} XY;

int main (int argc, char *argv[])
{
    MPI_Init(&argc, &argv);
    .
    .
    .
    const int num_items = 2;
    int blocklengths[2] = {1, 1};
    MPI_Aint offsets [2];
    offsets[0] = offsetof(XY, x);
    offsets[1] = offsetof(XY, y);
    MPI_Datatype types[2] = {MPI_INT, MPI_INT};
    MPI_Datatype mpi_new_type;

    MPI_Type_struct(...., &mpi_new_type);
    MPI_Type_commit(&mpi_new_type);

    // Call some function here depending on rank
    if (rank == 0)
        controlFunction(..);
    else
        someFunction(..);

    return 0;
}

int controlFunction(..)
{
    MPI_Recv(.., mpi_new_type,...);
    .
    .
}

int someFunction(..)
{
    MPI_Send(.., mpi_new_type,...);
    .
    .
}

So the basic idea is I create a struct with some data in it and create a new MPI_Datatype to handle the struct over MPI. The issue lies in controlFunction and someFunction where upon compiling my program using mpicc file.c -o file I get the error: mpi_new_type undeclared in both the functions.

Is there any way I can access this datatype in other functions?

Thanks.

EDIT - Added more code to show declarations of mpi_new_type as requested.

Upvotes: 1

Views: 319

Answers (1)

Adrian Panasiuk
Adrian Panasiuk

Reputation: 7343

The variable mpi_new_type is visible only in the scope of the body of the main function. The name is undeclared within the scopes of someFunction's and controlFunction's bodies. You can pass the variable as an argument to those

 int main() {   
 ...
 if (...)
    controlFunction(mpi_new_type, ...);
 else
    ...
 ...
 }

 int controlFunction(MPI_Dataype mpi_new_type, ...) {

or make it a global variable (although don't forget all the reasons why globals are discouraged.)

Upvotes: 3

Related Questions