문제

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?

도움이 되었습니까?

해결책 2

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;

다른 팁

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;

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;
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top