有关另一个union中的union字段的编译错误

时间:2014-03-07 02:00:20

标签: c unions

考虑下面的代码,我写了:

#include <stdio.h>
#include <stdint.h>

union myAccess {
    uint16_t access16;
    struct {
        uint8_t lo;
        uint8_t hi;
        } access8;
    };

union myByte{
    uint8_t  BYTE;
    struct {
        unsigned BIT0:1;
        unsigned BIT1:1;
        unsigned BIT2:1;
        unsigned BIT3:1;
        unsigned BIT4:1;
        unsigned BIT5:1;
        unsigned BIT6:1;
        unsigned BIT7:1;
        }BIT;
    };

int main()
{

   union myAccess U;
   U.access8.lo=0xF1;
   U.access8.hi=0x55;
   printf("%x\n",U);


   union myByte B;
   B.BYTE=0;
   B.BIT.BIT4=1;
   printf("%x\n",B);

    return 0;
}

输出结果为:

Gaurav@Gaurav-PC /cygdrive/d
$ ./LSI
2255f1
61279210

现在我修改我的代码如下:

#include <stdio.h>
#include <stdint.h>

union myAccess {
    uint16_t access16;
    struct {
        uint8_t lo;
        union myByte hi;//here
        } access8;
    };

union myByte{
    uint8_t  BYTE;
    struct {
        unsigned BIT0:1;
        unsigned BIT1:1;
        unsigned BIT2:1;
        unsigned BIT3:1;
        unsigned BIT4:1;
        unsigned BIT5:1;
        unsigned BIT6:1;
        unsigned BIT7:1;
        }BIT;
    };

int main()
{

    union myAccess U;
    U.access8.lo=0xF1;
    U.access8.hi.BYTE=0x55;
    printf("%x\n",U);
    return 0;
}

此处显示编译错误

Gaurav@Gaurav-PC /cygdrive/d
$ gcc -Wall LSI.c -o LSI
LSI.c:8: error: field `hi' has incomplete type
LSI.c: In function `main':
LSI.c:33: warning: unsigned int format, myAccess arg (arg 2)
LSI.c:33: warning: unsigned int format, myAccess arg (arg 2)

我做错了什么?

3 个答案:

答案 0 :(得分:2)

在第二个示例中,定义union myAccess时,其字段hi的类型为union myByte,但尚未定义该类型。您需要在union myByte之前添加union myAccess的定义。

答案 1 :(得分:2)

在您在其他myByte联盟中引用之前,您需要声明联合myAccess

Working example here.

答案 2 :(得分:0)

union myByte作为structmyAccess的成员使用之前,您没有声明myByte。编译器需要知道什么是类型myByte才能使用它。

尝试在myAccess中使用int main(void) { int a = 1, b = 1; c = a + b; int c; return c; } 作为类型在逻辑上等同于在声明它之前尝试使用变量:

c

这会抛出一个编译错误,声称{{1}}未声明。

相关问题