In the second example, when union myAccess
is defined, its field hi
has type union myByte
, but that type is not defined yet. You need to put the definition of union myByte
before union myAccess
.
Compilation error about a union field in another union
문제
Consider below code, I have written:
#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;
}
The output is:
Gaurav@Gaurav-PC /cygdrive/d
$ ./LSI
2255f1
61279210
Now when I modify my code as below:
#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;
}
It is showing compilation error at here
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)
What am I doing wrong?
해결책
다른 팁
You need to declare the union myByte
before you reference it within your other myAccess
union.
You are not declaring the union myByte
before using it in as a member of the struct
in myAccess
. The compiler needs to know what is the type myByte
before it can be used.
Trying to use myByte
as type in myAccess
is logically equivalent as trying to use a variable before declaring it:
int main(void) {
int a = 1, b = 1;
c = a + b;
int c;
return c;
}
This will throw a compilation error claiming that c
is undeclared.
제휴하지 않습니다 StackOverflow