Ras*_*yak 5 c embedded volatile
几天前我接受了采访,但仍然在寻找答案.我想了解使用volatile关键字的意义.
找到下面的代码:两种不同的场景.
//project1
//File1.c
int abc;//Global variable
/*And this variable is getting used in some other files too.*/
if(abc == 3) //Say
{
printf("abc == 3");
}
else
{
printf("abc != 3");
}
/*So if or else part will not be optimized
because "abc" can not be predicted,
the value can chage at any point of time */
//Project2
//file1.c
volatile int abc;//Global variable with volatile keyword
/*And this variable is getting used in some other files too.*/
if(abc == 3) //Say
{
printf("abc == 3");
}
else
{
printf("abc != 3");
}
/*So if or else part will not be optimized
because "abc" can not be predicted as it is declared as volatile,
the value can chage at any point of time */
Run Code Online (Sandbox Code Playgroud)
为什么我们应该使用volatile关键字呢?
正如Tony Delroy在其评论中解释的那样,外部和不稳定是完全不同的.
Volatile关键字可以保护您的变量不被积极优化.优化变量对于其他线程是不可见的,并且永远不会到达主存储器.有时,如果不需要,编译器甚至可以完全压缩变量.编译器根据您的源代码作为其唯一输入.有时,有一些外部事件可以改变您的变量值.例如,它可以是硬件设备或其他过程.
=>具体来说,编译器禁用对此变量的一些优化,因此它可以按照您的意愿运行.
Extern不是关于缓存与内存的关系.Extern只是访问一个存在于其他目标文件中的变量.请参阅此简短示例,了解为extern访问生成的汇编代码类型.这些外部变量尽可能在自己的目标文件中进行优化.毫无疑问是要保护它.
=>具体地说,编译器指示需要在链接时解决的外部引用
| 归档时间: |
|
| 查看次数: |
12618 次 |
| 最近记录: |