Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I make a variable temporarily volatile?

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.)

like image 995
SF. Avatar asked Mar 23 '26 18:03

SF.


1 Answers

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.

like image 121
Potatoswatter Avatar answered Mar 26 '26 09:03

Potatoswatter