我有这个 ProcessStasts.h
文件,它包含在另外两个 .h 文件中。
#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;
}
当我尝试编译时,出现此错误:
error LNK2005: MPI_Cust_ProcessStats_create(void) already defined
。如果我从文件之一中注释 #include "ProcessStasts.h"
指令和使用 ProcessStats 结构的行,它将正确编译。我什至尝试评论 ProcessStats 中依赖的所有行,只留下 #include "ProcessStasts.h"
语句,我得到这个 lnk 错误。怎么了? 最佳答案
你可以这样写:
首先是 ProcessStasts.h
#pragma once
#include <mpi.h>
#include <cstddef>
struct ProcessStats
{
int rank,
itLeft,
crtIt,
processFlag;
float speed;
};
MPI_Datatype MPI_Cust_ProcessStats_create();
然后是 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;
}
然后,您可以根据需要多次包含 ProcessStasts.h。建议不要在头文件中定义函数。
关于c++ - 编译包含结构的 h 文件时出现链接错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20141408/