gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 06:29:29 28 4
gpt4 key购买 nike

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

#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)

我做错了什么?

最佳答案

在第二个例子中,当定义了union myAccess时,它的字段hi的类型是union myByte,但是那个类型还没有定义.您需要将 union myByte 的定义放在 union myAccess 之前。

关于关于另一个 union 中 union 字段的编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22240029/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com