函数调用之间是否刷新全局变量? [英] Are global variables refreshed between function calls?

查看:151
本文介绍了函数调用之间是否刷新全局变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



当我有一个等待一些布尔标志的函数时,我会写入嵌入式固件,有时很难决定是否需要volatile。改变了一个中断,很明显,标志需要是挥发性的,因为这个函数会永远等待,因为编译器没有意识到这个值可以被中断改变。



但是当我有一个简单的函数只是检查第一行中的一个标志,我会期望该标志不需要是挥发性的,因为它的值将被读取每次我进入功能?所以当一个中断在第一次调用函数之间修改它的值,而第二次修改它的值时,我将得到新的值。还是不能保证每次输入函数时,所有缓存寄存器都被清除?

解决方案

你还需要标记你的变量 volatile :由于优化程序可以自由地内联您的函数,特别是较短的函数,调用您的函数循环中没有 volatile 标记用于访问硬件修改的内存将使您在初次迭代后不会读取内存的危险。


Im writing embedded firmware, and find it sometimes hard to decide when I need volatile or not.

When I have a function that waits for some boolean flag to be changed by an interrupt, it's obvious that the flag needs to be volatile, because else the function would wait forever, since the compiler doesn't realise the value can be changed by the interrupt.

But when I have a short function that just checks a flag in the first line, I would expect the flag doesnt need to be volatile, because its value will be read every time I enter the function? So when an interrupt modifies its value between the first time I call the function, and the second time, I will get the fresh value. Or is it not guaranteed that every time I enter the function all caching registers are cleared?

解决方案

You would still need to mark your variable volatile: since the optimizer is free to inline your functions, especially the short ones, calling your function in a loop without a volatile mark for accessing hardware-modified memory would place you in danger of not reading the memory after the initial iteration.

这篇关于函数调用之间是否刷新全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆