gpt4 book ai didi

c - volatile 和 extern 有什么区别?

转载 作者:太空狗 更新时间:2023-10-29 14:53:32 27 4
gpt4 key购买 nike

几天前我接受了采访,但我仍在寻找答案。我想了解使用 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com