Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Link error while compiling a h file containing a struct

Tags:

c++

struct

mpi

I have this ProcessStasts.h file that is included into two other .h files.

#pragma once

#include <mpi.h>
#include <cstddef>

struct ProcessStats
{
    int rank,
    itLeft,
    crtIt,
    processFlag;
    float speed;
};

MPI_Datatype MPI_Cust_ProcessStats_create()
{
    // set data to create new MPI data type
    MPI_Datatype MPI_Cust_ProcessStats;
    MPI_Datatype dataTypes[5] = {MPI_INT, MPI_INT, MPI_INT, MPI_INT, MPI_FLOAT};
    int blockLengths[5] = {1, 1, 1, 1, 1};
    MPI_Aint offsets[5];

    offsets[0] = (MPI_Aint) offsetof(ProcessStats, rank);
    offsets[1] = (MPI_Aint) offsetof(ProcessStats, itLeft);
    offsets[2] = (MPI_Aint) offsetof(ProcessStats, crtIt);
    offsets[3] = (MPI_Aint) offsetof(ProcessStats, processFlag);
    offsets[4] = (MPI_Aint) offsetof(ProcessStats, speed);

    // create new MPI type based on data from above
    MPI_Type_create_struct(5, blockLengths, offsets, dataTypes, &MPI_Cust_ProcessStats);
    MPI_Type_commit(&MPI_Cust_ProcessStats);

    return MPI_Cust_ProcessStats;
}

When I try compiling I get this error: error LNK2005: MPI_Cust_ProcessStats_create(void) already defined. If I comment the #include "ProcessStasts.h" directive and the line that uses the ProcessStats struct, from one of the files, it compiles correctly. I even tryed to comment all lines dependent in ProcessStats and only leave the #include "ProcessStasts.h" statements and I get this lnk error. What is wrong?

like image 346
codiac Avatar asked May 12 '26 00:05

codiac


1 Answers

You can write like this: first is ProcessStasts.h

#pragma once

#include <mpi.h>
#include <cstddef>

struct ProcessStats
{
    int rank,
    itLeft,
    crtIt,
    processFlag;
    float speed;
};

MPI_Datatype MPI_Cust_ProcessStats_create();

then is ProcessStasts.c

#include "ProcessStats.h"
MPI_Datatype MPI_Cust_ProcessStats_create()
{
    // set data to create new MPI data type
    MPI_Datatype MPI_Cust_ProcessStats;
    MPI_Datatype dataTypes[6] = {MPI_INT, MPI_INT, MPI_INT, MPI_INT, MPI_FLOAT};
    int blockLengths[5] = {1, 1, 1, 1, 1};
    MPI_Aint offsets[5];

    offsets[0] = (MPI_Aint) offsetof(ProcessStats, rank);
    offsets[1] = (MPI_Aint) offsetof(ProcessStats, itLeft);
    offsets[2] = (MPI_Aint) offsetof(ProcessStats, crtIt);
    offsets[3] = (MPI_Aint) offsetof(ProcessStats, processFlag);
    offsets[4] = (MPI_Aint) offsetof(ProcessStats, speed);

    // create new MPI type based on data from above
    MPI_Type_create_struct(3, blockLengths, offsets, dataTypes, &MPI_Cust_ProcessStats);
    MPI_Type_commit(&MPI_Cust_ProcessStats);

    return MPI_Cust_ProcessStats;
}

Then you can include the ProcessStasts.h as many times as you want. As a suggestion, do not define functions in a head file.

like image 161
yanchong Avatar answered May 14 '26 15:05

yanchong