C 全局匿名结构/联合 [英] C global anonymous struct / union

查看:43
本文介绍了C 全局匿名结构/联合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 uint64 变量,它通常只需要高或低 32 位访问.我正在使用 32 位 ARM Cortex M0,为了提高速度,我试图将 uint64 变量与 C 中的两个 uint32 变量重叠,使用匿名结构,希望避免使用指针算法来访问成员.

I have a uint64 variable which often only requires high or low 32 bit access. I am using a 32-bit ARM Cortex M0, and to help with speed and I am trying to overlap the uint64 variable with two uint32 variables in C, using anonymous structures in the hope of avoiding pointer arithmetic to access members.

我正在尝试做的事情可能吗?使用命名联合可能同样快,但现在我很好奇是否可以不使用它.以下未成功编译:

Is what I am trying to do possible? It could be that using a named union is just as fast, but now I'm just intrigued if it can be done without. The following does not compile successfully:

http://goo.gl/ejx37y

#include <stdint.h>

volatile union {
  uint64_t ab;
  struct { uint32_t a, b; };
};

int main(void)
{
  a = 1;
};

推荐答案

根本不可能那样做.全局变量(如您在头文件中声明的那些)与匿名结构或联合的成员不同,这根本行不通.

It's simply not possible to do like that. A global variable (like the ones you declare in the header file) are not the same as members of an anonymous structure or union, that simply wont work.

并且具有匿名结构或联合对指针运算没有帮助,该结构仍将位于内存中的某个位置,并且编译器使用结构基地址的偏移量来找出成员的位置.然而,由于基地址和成员偏移量在编译时都是已知的,编译器通常能够生成直接访问成员的代码,就像任何其他变量一样.如果不确定,请查看生成的代码.

And having anonymous structures or unions won't help with pointer arithmetic, the structure will still sit somewhere in memory, and the compiler uses offsets from the structures base-address to find out where the members are. However, since both the base-address and member offsets are know at time of compilation, the compiler will generally be able to generate code to access the member directly, just like any other variable. Look at the generated code if you are unsure.

因此跳过匿名结构的废话,在头文件中正确定义它们,并在头文件中声明这些结构的变量,同时在某些源文件中定义这些变量.

So skip the nonsense with anonymous structures, define them properly in the header files, and declare variables of those structures in the header files too, while defining those variables in some source file.

对于头文件:

union you_union
{
    uint64_t ab;
    struct { uint32_t a, b; };
};

extern union your_union your_union;

在源文件中

union your_union your_union;

这篇关于C 全局匿名结构/联合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆