联合中的匿名结构问题

时间:2012-07-24 07:44:53

标签: gcc struct union

我有这样的事情:

union MyBBox3D
{
    struct
    {
        float  m_fBox[6]; 
        float  m_fCenter[3];
        float  m_fDiagonalLen;
        float  m_fNormalizeFactor;
        float  m_fScaling[3];
    };
    struct
    {
        float  m_fMin[3];
        float  m_fMax[3];
        float  m_fCenter[3]; 
        float  m_fDiagonalLen;
        float  m_fNormalizeFactor;
        float  m_fScaling[3];
    };
    struct
    {
        float  m_fMinX, m_fMinY, m_fMinZ;
        float  m_fMaxX, m_fMaxY, m_fMaxZ;
        float  m_fCenterX, m_fCenterY, m_fCenterZ;
        float  m_fDiagonalLen;
        float  m_fNormalizeFactor;
        float  m_fScalingX, m_fScalingY, m_fScalingZ;
    };
};

它与vs2008和intel编译器12.0编译得很好,但是不能用gcc4.6.3编译,它会出现以下错误:

In file included from Mesh/MyMeshTool.cpp:17:0:
Mesh/MyMeshTool.h:68:28: error: declaration of ‘float                   nsMeshLib::MyBBox3D::<anonymous struct>::m_fCenter [3]’
Mesh/MyMeshTool.h:59:28: error: conflicts with previous declaration ‘float nsMeshLib::MyBBox3D::<anonymous struct>::m_fCenter [3]’
Mesh/MyMeshTool.h:69:17: error: declaration of ‘float nsMeshLib::MyBBox3D::<anonymous struct>::m_fDiagonalLen’
Mesh/MyMeshTool.h:60:17: error: conflicts with previous declaration ‘float nsMeshLib::MyBBox3D::<anonymous struct>::m_fDiagonalLen’
Mesh/MyMeshTool.h:70:20: error: declaration of ‘float nsMeshLib::MyBBox3D::<anonymous struct>::m_fNormalizeFactor’
Mesh/MyMeshTool.h:61:20: error: conflicts with previous declaration ‘float nsMeshLib::MyBBox3D::<anonymous struct>::m_fNormalizeFactor’
Mesh/MyMeshTool.h:71:32: error: declaration of ‘float nsMeshLib::MyBBox3D::<anonymous struct>::m_fScaling [3]’
Mesh/MyMeshTool.h:62:32: error: conflicts with previous declaration ‘float nsMeshLib::MyBBox3D::<anonymous struct>::m_fScaling [3]’
Mesh/MyMeshTool.h:78:17: error: declaration of ‘float nsMeshLib::MyBBox3D::<anonymous struct>::m_fDiagonalLen’
Mesh/MyMeshTool.h:60:17: error: conflicts with previous declaration ‘float nsMeshLib::MyBBox3D::<anonymous struct>::m_fDiagonalLen’
Mesh/MyMeshTool.h:79:20: error: declaration of ‘float nsMeshLib::MyBBox3D::<anonymous struct>::m_fNormalizeFactor’
Mesh/MyMeshTool.h:61:20: error: conflicts with previous declaration ‘float nsMeshLib::MyBBox3D::<anonymous struct>::m_fNormalizeFactor’

我该如何解决这个问题?提前谢谢!

2 个答案:

答案 0 :(得分:1)

我认为在这种情况下(构成联合共享标识符名称的单独结构),使用匿名结构你可能更好 not

要么在整个联盟中使名称唯一。

其他任何事情只是在寻找麻烦: - )

答案 1 :(得分:0)

如果您将-fms-extensions程序选项传递给gcc调用,则最近的GCC会接受unamed fields,但这是标准C99规范的扩展。

您也可以小心使用预处理器技巧,例如

union myunion {
  struct {
     int fa_u1;
     int fb_u1;
  } u1;
#define fa u1.fa_u1
#define fb u1.fb_u1
  struct {
     double fc_u2;
     char fd_u2[8];
  } u2;
#define fc u2.fc_u2
#define fd u2.fd_u2
}

然后您可以代码x.fa代替x.u1.fa_u1等。谨慎使用预处理器技巧(请记住#define具有完整的翻译单元范围)。实际上,您希望fau1fa_u1名称长且唯一。