当前位置:中国高校自动化网 >> DSP >> 浏览文章

关于关键字 volatile

文章来源:EDN博客 访问次数:


本文来自beethoven的博客,讲述了关于关键字 volatile, 作者博客:http://blog.ednchina.com/beethoven

来自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学习资料
下一篇:CCS中文教程
最近更新