gpt4 book ai didi

gcc - 如何使用 C/gcc 从外围 IO 寄存器中读取数据?

转载 作者:行者123 更新时间:2023-12-04 14:58:04 24 4
gpt4 key购买 nike

我在 AVR32 上有一个中断服务路由。我需要从中断状态寄存器中读取以取消中断。但是我不使用读取的结果。我宁愿不使用 asm 指令,但我担心 gcc 会优化对虚拟变量的读取。什么是正确的方法?

目前我有:

uint32_t tmp = *(volatile uint32_t *)INTERRUPT_STATUS_REG_ADDRESS;

tmp 也应该是 volatile 吗?我担心如果不使用 tmp,gcc 会跳过读取。

最佳答案

通过指针强制转换为 (volatile uint32_t*) 读取中断状态寄存器告诉编译器读取此表达式(指定地址处的变量)会产生副作用,因此它始终需要评估此表达式。

由于您的 tmp 变量不是 volatile 的,编译器可以自由地优化将寄存器的值存储到变量中。

我认为 C 标准的第 5.1.2.3 章 (see here)足够相关。

另外第 6.7.3 章解释了:

An object that has volatile-qualified type may be modified in ways unknown to the implementation or have other unknown side effects. Therefore any expression referring to such an object shall be evaluated strictly according to the rules of the abstract machine, as described in 5.1.2.3. Furthermore, at every sequence point the value last stored in the object shall agree with that prescribed by the abstract machine, except as modified by the unknown factors mentioned previously. 116) What constitutes an access to an object that has volatile-qualified type is implementation-defined.



您实际上可以省略 tmp 并只写:
*(volatile uint32_t *)INTERRUPT_STATUS_REG_ADDRESS;

这将简单地读取位于 INTERRUPT_STATUS_REG_ADDRESS 的 uint32_t 寄存器;

关于gcc - 如何使用 C/gcc 从外围 IO 寄存器中读取数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26475335/

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