c - volatile 和 extern 有什么区别?

标签 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 */

为什么我们应该改用 volatile 关键字?

最佳答案

正如 Tony Delroy 在其评论中解释的那样,externvolatile是完全不同的。


Volatile 关键字保护您的变量不被过度优化。优化的变量可以对其他线程不可见,并且永远不会到达主内存。有时,编译器可以 even squeeze entirely如果不需要,则为变量。编译器将您的源代码作为其唯一输入进行猜测。有时,有一些外部事件可以改变你的变量值。例如,它可以是硬件设备或其他进程。

=> 具体来说,编译器禁用了对该变量的一些优化,因此它可以按您希望的方式运行。


Extern 与缓存与内存无关。 Extern 只是访问一个存在于其他目标文件中的变量。参见 this short exampleextern 访问生成何种汇编代码。 那些 extern 变量在它们自己的目标文件中被尽可能地优化。保护不保护是毫无疑问的。

=> 具体来说,编译器指出一个外部引用需要在链接时解决

关于c - volatile 和 extern 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9173492/

相关文章:

c# - float 比双倍慢吗? 64位程序运行速度比32位程序快吗?

c - 如何在 Tensorflow Lite(实验 C API)中创建输入张量并与解释器一起使用?

c - 如何在设备驱动程序和它控制的 FPGA 之间共享寄存器和位域定义

linux - 嵌入式Linux : Hardware access

java - java中的初始值之后, volatile 映射可以为空吗?

c - 这些语法的含义(指针算术?)

c - 可以使用 execvp 和 fork 退出和更改目录的简单 Shell

c - 如何在代码段中运行每个 "function"?

c# - C# 和 C++ 中的 volatile 关键字

Java - 仅在多处理器系统中使用 volatile 才有意义?