问题
In PSoC, one can declare variables in memory space mapped to flash. Since flash reads are slower than RAM reads, the program would benefit from compiler optimizations - allow the values to be stored in registers or otherwise cached. Except for when one modifies the value of the flash. This can be done on the fly and the programmer knows the precise moments that happens. This also is done relatively rarely (to protect flash from write wear) and takes relatively long time. In case of such a write it would be good if the variable were to restore its value from the underlying memory (behave like volatile), and then proceed as usually, with all optimizations until next write.
So, in essence, some mechanism that forces refreshing the variables by using their underlying memory cells would be useful; be it restricted time-wise (shortly after write) or to some section of code (a jump to a 'refresh' function after write operation). Is there any such mechanism in C generally, or in GCC specifically?
(Also, considering memory constraints (2-4KB RAM) it would be desirable if allocation of RAM/registers was left to optimizer - the trivial approach of having each variable mirrored in two persistent versions: volatile (in Flash) and non-volatile (in RAM), rewriting volatile to non-volatile during refresh and then using the non-volatile everywhere from then on would be rather wasteful.)
回答1:
You should do the caching yourself by explicitly maintaining a variable in RAM. The CPU very often won't have a register available, and the compiler won't use the stack to cache a global.
You can try declaring the variable non-volatile and then accessing it through a volatile pointer, such as by * (volatile int *) & foo. Personally, I would call that a recipe for disaster. It likely won't update the "cached" value of foo.
Doing the reverse and declaring it volatile but removing the qualification with a pointer, would produce undefined behavior. The compiler likely won't hoist the pointer dereference to registers anyway.
回答2:
You could try using two variables:
int foo;
volatile int foo_vol;
Use foo for most of your program, but when a write occurs, assign foo_vol to foo.
if (there_was_a_write)
foo = foo_vol;
process_data(&foo, bar);
This will cause foo to get the optimizations, but it can still use the new value. I'm not sure if this approach would work for your particular setup, but good luck anyway.
来源:https://stackoverflow.com/questions/25614616/can-i-make-a-variable-temporarily-volatile