Interpretation of the Volatile

Always wanted to see volatile usage, before you seen this amount is not static inadvertent destruction of the compiler, but has not been completely clear out.

Today we see a lot of the older generation of summary, and I had a new experience, wrote this essay to share their experiences.

Came into contact with the volatile is __IO STM32 program, wherein #define __IO volatile

(The following paragraph from Wikipedia's interpretation of Volatile)

volatile keyword is used to prevent the (pseudo) compiler can not think of "the code itself is" changing the code (variable / object) is optimized. As in the C language,

volatile time variable key may be used to alert it later defined compiler may change at any time, so the compiled program each time it needs to store or read this variable, the variable will directly read data from the address. Without the volatile keyword, the optimizing compiler may read and store, may temporarily use the value in the register, if this variable is updated by the other program, it will appear inconsistencies.

(The above paragraph from Wikipedia's interpretation of Volatile)

In the C language, the compiler will have to be optimized based on your code, and volatile most direct is to tell the compiler not to optimize the operation process this variable.

(Picture below from Wikipedia)

(Picture above from Wikipedia)

In the compilation, it can be clearly seen after use Volatile compiler will not let you lose the code.

Let me talk about the benefits of using volatile:

1.volatile allow the event to change the program in addition to its content, such as changing the hardware directly.

2. Each of the volatile content is read directly access the contents of the address, not by Cache ( Cache accessed).

A little explain: 1. We tell the compiler, volatile types of variables may indeed be changing external conditions, such as hardware.

2. Under normal circumstances, if we do not add volatile, then the variable program shared address areas did not know when it was changed, you may only be read cache inside the variable, and this variable may be out of date variables.

3.(补充)私有地址里面的内容,程序可以直接访问

 

回到我们的截图内容

#define __IO  volatile

#define uint32_t  uisigned long

如果是(volatile unsigned long *) (0x1FFF7A10),再分解看(volatile unsigned long *)是一个为随硬件需要定义的一种地址,前面加上*指针,即直接指向改地址,整个定义#define CPU_Sn0,调用的时候直接向地址寄存器写内容就好了。这是内存机制的方便性,volatile是嵌入式系统开发发一个重要特点。

再将其展开来分析:(volatile unsigned long *) (0x1FFF7A10)的意思就是将0x1FFF7A10强制转化成volatile unsigned long的指针,然后赋给CPU_Sn0就是表达CPU_Sn0为指向地址的内容了。这里是通过内存寻址访问寄存器,可以进行读/写操作。

再通过这个volatile去分析,关键字volatile 确保本条指令不会因C 编译器的优化而被省略,且要求每次直接读值。例如用while((unsigned char *)0x1FFF7A10)时,有时系统可能不真正去读0x1FFF7A10的值,而是用第一次读出的值,如果这样,那这个循环可能是个死循环。用了volatile 则要求每次都去读0x1FFF7A10的实际值。那么它就是一个固定的指针,而char *p;是一个指针变量。

再在前面加一个 “*” :则变成了变量,只不过这是一个地址固定的指针变量。

Guess you like

Origin www.cnblogs.com/qiaoyonggang/p/11256340.html