在 C 语言中,如何将结构体的成员声明为易失性的?
如何将结构体的特定成员声明为易失性?
How do you declare a particular member of a struct as volatile?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
如何将结构体的特定成员声明为易失性?
How do you declare a particular member of a struct as volatile?
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(4)
与非
struct
字段完全相同:您可以使用
"volatile struct _a {...}"
将整个struct
标记为易失性。但上面的方法是针对个别字段的。Exactly the same as non-
struct
fields:You can mark the entire
struct
as volatile by using"volatile struct _a {...}"
but the method above is for individual fields.根据这篇文章应该非常简单:
Should be pretty straight forward according to this article:
我需要澄清 C/C++ 的 易失性,因为这里有一个错误的答案。 我自 1994 年以来一直在对微控制器进行编程,这个关键字非常有用并且经常需要。
易失性永远不会破坏你的代码,使用它永远不会有风险。 该关键字基本上将确保该变量不会被编译器优化。 如果你过度使用这个关键字,最糟糕的情况是你的程序会变得更大、更慢。
这是当你需要这个关键字作为变量时:
- 您有一个写入中断函数内部的变量。
和
- 这个相同的变量被读取或写入到外部中断函数。
或者
如果您有 2 个不同优先级的中断函数使用该变量,那么您还应该使用“易失性”。
否则,不需要该关键字。
至于硬件寄存器,如果你不在程序中做奇怪的事情,即使没有关键字,它们也应该被视为易失性的。
I need to clarify volatile for C/C++ because there was a wrong answer here. I've been programming microcontroleurs since 1994 where this keyword is very useful and needed often.
volatile will never break your code, it is never risky to use it. The keyword will basically make sure the variable is not optimized by the compiler. The worst that shold happen if you overuse this keyword is that your program will be a bit bigger and slower.
Here is when you NEED this keyword for a variable :
- You have a variable that is written to inside an interrupt function.
AND
- This same variable is read or written to outside interrupt functions.
OR
If you have 2 interrupt functions of different priority that use the variable, then you should also use 'volatile'.
Otherwise, the keyword is not needed.
As for hardware registers, they should be treated as volatile even without the keyword if you don't do weird stuff in your program.
我刚刚完成了一个数据结构,其中很明显需要 volatile 限定符,但原因与上述不同:这只是因为该结构需要强制锁定机制,因为 (i) 直接访问 和(ii) 等效调用。
直接访问 处理持续的 RAM 读写。
等效调用 处理可互换的方法流。
我没有除非编译器确切地知道如何处理它,否则这个关键字很幸运。 这是我个人的经历。 但我有兴趣研究它如何直接影响跨平台编译,例如低级系统调用和后端数据库之间的编译。
I just finished a data structure in which it was obvious where the volatile qualifier was required, but for a different reason than the ones stated above: It is simply because the struct requires a forceful locking mechanism because of (i) direct access and (ii) equivalent invocation.
Direct access deals with sustained RAM reading and writing.
Equivalent invocation deals with interchangeable method flows.
I haven't had much luck with this keyword unless the compiler knows exactly what to do about it. And that's my own personal experience. But I am interested in studying how it directly impacts a cross-platform compilation such as between a low-level system call and a back-end database.