asimes
asimes

Reputation: 6130

C, MPI variable scope

I'm looking at someone else's MPI code and there are a number of times that variables are declared in main() and used in other functions (some MPI specific). I am new to MPI, but in my programming experience that is normally not supposed to be done. Basically it is difficult for me to determine if it is safe to do this (no errors are thrown).

The entire code is quite long so I will just give a simplified version below:

int main(int argc, char** argv) {
    // ...unrelated code
    int num_procs, local_rank, name_len;
    MPI_Comm comm_new;

    MPI_Init(&argc, &argv);
    MPI_Get_processor_name(proc_name, &name_len);

    create_ring_topology(&comm_new, &local_rank, &num_procs);
    // ...unrelated code

    MPI_Comm_free(&comm_new);
    MPI_Finalize();
}

void create_ring_topology(MPI_Comm* comm_new, int* local_rank, int* num_procs) {    
    MPI_Comm_size(MPI_COMM_WORLD, num_procs);

    int dims[1], periods[1];
    int dimension = 1;
    dims[0] = *num_procs;
    periods[0] = 1;
    int* local_coords = malloc(sizeof(int)*dimension);

    MPI_Cart_create(MPI_COMM_WORLD, dimension, dims, periods, 0, comm_new);
    MPI_Comm_rank(*comm_new, local_rank);
    MPI_Comm_size(*comm_new, num_procs);
    MPI_Cart_coords(*comm_new, *local_rank, dimension, local_coords);
    sprintf(s_local_coords, "[%d]", local_coords[0]);
}

Upvotes: 2

Views: 712

Answers (1)

Adam
Adam

Reputation: 17389

That's just regular pointer usage. Nothing wrong with that.

The variables are declared in main and remain in-scope until main returns, i.e. almost for the duration of the program.

Note that MPI does not actually add anything to C. All it is is an extra library. It does not extend the language.

Upvotes: 3

Related Questions