TChapman500
TChapman500

Reputation: 137

C++ typedef union compile error

I'm getting some interesting errors in VC++2010 Express when I try to define a couple of unions and inline functions for those unions. I'm trying to build a static library to use in a number of programs.

typedef union
{
    double data[3];
    struct { double x, y, z; };
} VECTOR3;

inline VECTOR3 _V3(double x, double y, double z)
{
    VECTOR3 vec = { x, y, z };
    return vec;
}

typedef union
{
    double data[9];
    struct { double x0, y0, z0, x1, y1, z1, x2, y2, z2; };
} MATRIX3;

inline MATRIX3 _M3(double x0, double y0, double z0, double x1, double y1, double z1, double x2, double y2, double z2)
{
    MATRIX3 mat3 = { x0, y0, z0, x1, y1, z1, x2, y2, z2 };
    return mat3;
}

This code is producing error "C2371: redefinition; different basic types" but this is the only place where these unions are defined.

The inline functions produce error "C2084: function 'FunctionName(ArgumentType)' already has a body" yet there are no other bodies defined. Either in this file, or in any files that are referenced.

Furthermore, code like the one shown here is in an SDK for another application. And builds using that SDK do not produce any of these errors.

None of my searches have been of any help.

Upvotes: 1

Views: 618

Answers (1)

Pierre Fourgeaud
Pierre Fourgeaud

Reputation: 14530

I suppose that this code is in a header file (.h).

You need to have include guards:

#ifndef YOUFILE_h__
# define YOUFILE_h__

// Your code

#endif // !YOUFILE_h__

It avoid multiple inclusion of the same file in a same translation unit.

If this header file is included many times (sometimes through other headers) in the same source file, then your unions will be defined more than once unless you have include guards.

Upvotes: 1

Related Questions