【发布时间】:2018-12-05 09:10:46
【问题描述】:
我处于一个包含多个元素的匿名结构的位置。为了通过索引访问它们,我将它们放在一个联合中,如下所示:
union
{
struct
{
unsigned char COMMAND; //STRUCT_ARRAY[0]
unsigned char ADDR_H; //STRUCT_ARRAY[1]
unsigned char ADDR_M; //STRUCT_ARRAY[2]
unsigned char ADDR_L; //STRUCT_ARRAY[3]
unsigned char DATA; //STRUCT_ARRAY[4]
unsigned char CHECKSUM; //STRUCT_ARRAY[5]
};
unsigned char STRUCT_ARRAY[6];
//all of the struct members can be accessed from STRUCT_ARRAY by index
}MY_UNION;
此联合当前位于文件 source.c 中。我需要从main.c 访问它。我有一个两个文件都包含的标题,我们称之为header.h。
如何在 main.c 中读取 ADDR_H 和 ADDR_M 的值,同时定期从 source.c 修改它?
代码有点像这样:
source.c:
#include "header.h"
union
{
struct
{
unsigned char COMMAND; //STRUCT_ARRAY[0]
unsigned char ADDR_H; //STRUCT_ARRAY[1]
unsigned char ADDR_M; //STRUCT_ARRAY[2]
unsigned char ADDR_L; //STRUCT_ARRAY[3]
unsigned char DATA; //STRUCT_ARRAY[4]
unsigned char CHECKSUM; //STRUCT_ARRAY[5]
};
unsigned char STRUCT_ARRAY[6];
//all of the struct members can be accessed from STRUCT_ARRAY by index
}MY_UNION;
void modify(void)
{
MY_UNION.ADDR_H = somevalue;
MY_UNION.ADDR_M = somevalue;
MY_UNION.ADDR_L = somevalue;
}
在 main.c 中:
#include "header.h"
void main(void)
{
modify();
print(MY_UNION.ADDR_H); //custom function to print values to a screen
print(MY_UNION.ADDR_M);
print(MY_UNION.ADDR_L);
}
【问题讨论】:
-
外部关键字?