【问题标题】:forward declarations of structures throwing a redefinition error结构的前向声明引发重定义错误
【发布时间】:2014-08-08 19:59:32
【问题描述】:

此代码正在使用 gcc 在 C 中的不同环境中正常编译和运行。我正在使用 g++ 将其移植到新的 C++ 环境中,但出现重新定义错误。

我见过类似的问题,但我的问题可能源于我在结构定义中有预先声明并且需要在实例化中再次预先声明的事实。以下是相关代码:

transaction.h

...
typedef int ( *pfnTrans)(transaction *);

typedef struct tag_TRANSTEP transStep;  //forward declare this for the following struct.

typedef struct tag_RETURNMAP
{
    int         onThisReturn;
    transStep * runThis;
}returnMap;

#define MAX_BRANCHES 10
struct tag_TRANSTEP
{
    pfnTrans thisStepsFunction;
    returnMap retMap[MAX_BRANCHES];
};
...

source.cpp

...

//Forward declaring the steps, since they reference one another.
transStep tsConsultChoreList;
transStep tsPayBills;
transStep tsMowLawn;
transStep tsFixLawnMower;

transStep tsConsultChoreList = {fnConsultChoreList, {{MOW_LAWN, &tsMowLawn},
                                                     {PAY_BILLS, &tsPayBills},
                                                     {0, NULL}}}; // this entry signifies end of returnMap
transStep tsPayBills=          {fnPayBills,         {{SUCCESS, &fnConsultChoreList},
                                                     {0, NULL}}}; // this entry signifies end of returnMap
transStep tsMowLawn=           {fnMowLawn,          {{SUCCESS, &tsConsultChoreList},
                                                     {FIX_MOWER, &tsFixLawnMower},
                                                     {0, NULL}}}; // this entry signifies end of returnMap
transStep tsFixLawnMower=      {fnFixLawnMower,     {{SUCCESS, &tsMowLawn},
                                                     {0, NULL}}}; // this entry signifies end of returnMap
...

我没有从 .h 文件中得到任何错误,但对于 .cpp 中的每个 transStep,我都会收到“重新定义 ...”错误和伴随的“...之前在此处声明”错误。

【问题讨论】:

    标签: struct g++ typedef forward-declaration redefinition


    【解决方案1】:

    这在 C 中是合法的吗?这在 C++ 中是不合法的。如果你在“预声明”前面加上extern,那么

    extern transStep tsConsultChoreList;
    extern transStep tsPayBills;
    // etc...
    

    它应该工作。在您的 .h 文件中,您要预先声明类型,而不是类型的实例。在您的 .cpp 文件中,您正在声明实际实例,告诉编译器为它们分配空间。 extern 关键字告诉编译器该变量存在,就在其他地方。那么你的初始化声明应该可以正常工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-11
      • 1970-01-01
      • 2012-06-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多