我在开发中也常常遇到这个问题, 发现通常用在两个方面, 一方面是对硬件寄存器或固定内 存的访问,一般要用到,这就是我们常常在寄存器的头文件常常看到的,另一个就是在多线 程,或主程序和中断共享,全局变量常常用到。言归正传,看看老外是怎么说的:
Introduction to the Volatile Keyword 认识关键字
Volatile The use of volatile is poorly understood by many programmers. This is not surprising, as most C t exts dismiss it in a sentence or two. 很多程序员对于 volatile 的用法都不是很熟悉。这并不奇怪,很多介绍 C 语言的书籍对于他 的用法都闪烁其辞。
Have you experienced any of the following in your C/C++ embedded code? ? Code that works fine-until you turn optimization on ? Code that works fine-as long as interrupts are disabled ? Flaky hardware drivers ? Tasks that work fine in isolation-yet crash when another task is enabled 在你们使用 C/C++语言开发嵌入式系统的时候,遇到过以下的情况么? ? 一打开编译器的编译优化选项,代码就不再正常工作了; ? 中断似乎总是程序异常的元凶; ? 硬件驱动工作不稳定; ? 多任务系统中,单个任务工作正常,加入任何其他任务以后,系统就崩溃了。
If you answered yes to any of the above, it's likely that you didn't use the C keyword volatile. You aren't alone. The use of volatile is poorly understood by many programmers. This is not surprising, as most C texts dismiss it in a sentence or two. 如果你曾经向别人请教过和以上类似的问题,至少说明,你还没有接触过 C 语言关键字 volatile 的用法。这种情况,你不是第一个遇到。很多程序员对于 volatile 都几乎一无所知。 大部分介绍 C 语言的文献对于它都闪烁其辞。
volatile is a qualifier that is applied to a variable when it is declared. It tells the compiler that the v alue of the variable may change at any time-without any action being taken by the code the compil er finds nearby. The implications of this are quite serious. However, before we examine them, let's take a look at the syntax. Volatile 是一个变量声明限定词。它告诉编译器,它所修饰的变量的值可能会在任何时刻被 意外的更新,即便与该变量相关的上下文没有任何对其进行修改的语句。造成这种“意外更 新”的原因相当复杂。在我们分析这些原因之前,我们先回顾一下与其相关的语法。
Syntax 语法
To declare a variable volatile, include the keyword volatile before or after the data type in the varia ble definition. For instance both of these declarations will declare foo to be a volatile integer: 要想给一个变量加上 volatile 限定,只需要在变量类型声明附之前/后加入一个 volatile 关键 字就可以了。 下面的两个实例是等效的, 它们都是将 foo 声明为一个“需要被实时更新”的 int 型变量。
volatile int foo; int volatile foo;
Now, it turns out that pointers to volatile variables are very common. Both of these declarations de clare foo to be a pointer to a volatile integer: 同样,声明一个指向 volatile 型变量的指针也是非常类似的。下面的两个声明都是将 f