C全局匿名struct/union [英] C global anonymous struct / union

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

问题描述

我有一个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全局匿名struct/union的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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