关于关键字 volatile

来自CCS的help:
The compiler analyzes data flow to avoid memory accesses whenever possible. If you have code that depends on memory accesses exactly as written in the C/C++ code you must use the volatile keyword to identify these accesses. A variable qualified with a volatile keyword is allocated to an uninitialized section (as opposed to a register). The compiler does not optimize out any references to volatile variables.

In the following example, the loop waits for a location to be read as 0xFF:

unsigned int *ctrl;
while (*ctrl !=0xFF);

In this example, *ctrl is a loop-invariant expression, so the loop is optimized down to a single memory read. To correct this, define *ctrl as:

volatile unsigned int *ctrl;

Here the *ctrl pointer is intended to reference a hardware location, such as an interrupt flag.

来自软工吧论坛
volatile提醒编译器它后面所定义的变量随时都有可能改变,因此编译后的程序每次需要存储或读取这个变量的时候,都会直接从变量地址中读取数据。如果没有volatile关键字,则编译器可能优化读取和存储,可能暂时使用寄存器中的值,如果这个变量由别的程序更新了的话,将出现不一致的现象。下面举例说明。

在DSP开发中,经常需要等待某个事件的触发,所以经常会写出这样的程序:
以下内容为程序代码:
short flag;
void test()
{
do1();
while(flag==0);
do2();
}

这段程序等待内存变量flag的值变为1之后才运行do2()。变量 flag的值由别的程序更改,这个程序可能是某个硬件中断服务程序,例如如果某个按钮按下的话,就会对DSP产生中断,在按键中断程序中修改flag为 1,这样上面的程序就能够得以继续运行。

但是,编译器并不知道flag的值会被别的程序修改,因此在它进行优化的时候,可能会把flag的值先读入某个寄存器,然后等待那个寄存器变为 1。如果不幸进行了这样的优化,那么while循环就变成了死循环,因为寄存器的内容不可能被中断服务程序修改。为了让程序每次都读取真正flag变量的值,就需要定义为如下形式:

volatile short flag;

需要注意的是,没有volatile也可能能正常运行,但是可能修改了编译器的优化级别之后就又不能正常运行了。因此经常会出现debug版本正常,但是release版本却不能正常的问题。所以为了安全起见,只要是等待别的程序修改某个变量的话,就加上volatile关键字。
 

原文地址:https://www.cnblogs.com/fpga/p/1570047.html