Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error: Redefinition of union

In the following code:

typedef struct
{
    union U
        {
            int a;
            char b;
        }U1;
}A;

typedef struct
{
    union U
        {
            int a;
            char b;
        }U1;
}B;

The compiler gives an error "[Error] redefinition of 'union U' ". But these unions are members of different structures. So generally there is no chance of variable name interference. So what can be the reason for this error?

like image 724
Ginu Jacob Avatar asked Feb 05 '14 05:02

Ginu Jacob


3 Answers

There's no separation of names into namespaces there, you actually are trying to redefine.

The snippet:

typedef struct { union U { int a; char b; } U1; } A;

has no significant difference here to:

union U { int a; char b; };
typedef struct { union U U1; } A;

You can solve it by simply introducing artificial namespaces to your types:

typedef struct { union AU { int a; char b; } U1; } A;
typedef struct { union BU { int a; char b; } U1; } B;

or, if the union is meant to be (and will remain) the same type, just define it once:

union U { int a; char b; };
typedef struct { union U U1; } A;
typedef struct { union U U1; } B;
like image 191
paxdiablo Avatar answered Nov 18 '22 20:11

paxdiablo


The name 'U' in your example is the name of the union union, while 'U1' is the name of the instance of the union within each of the structs 'A' and 'B'. U1 can be re-used but the name 'U' has scope throughout the file.

You could have done this:

typedef struct
{
    union U
        {
            int a;
            char b;
        }U1;
}A;

typedef struct
{
    union U U1;
}B;

since both A.U1 and B.U1 have the same declaration. Otherwise, you'd have to use different names for the union.

Or, just use anonymous unions (ie. do not provide a name for the union at all):

typedef struct
{
    union
        {
            int a;
            char b;
        }U1;
}A;

typedef struct
{
    union
        {
            int a;
            char b;
        }U1;
}B;
like image 42
harmic Avatar answered Nov 18 '22 21:11

harmic


Even if you could define the two unions named U, it wouldn't be very useful. After all, which union would you be referring to if you created a union U variable? If you intend to create such variables, then give diferent names for the unions to disambiguate. On the other hand, if you never never intend to create such variables, then you can consider using anonymous unions:

typedef struct {
    union {
        int a;
        char b;
    }U1;
}A;

typedef struct {
    union {
        int a;
        char b;
    }U1;
}B;
like image 25
hugomg Avatar answered Nov 18 '22 21:11

hugomg