I have some embedded code that writes commands to a memory address to control a peripherial like so:
void intelStartEraseBlock(uint16_t *wordAddress) {
*wordAddress = 0x20; //block erase
*wordAddress = 0xD0; //block erase confirm
}
I suspect that the optimizer is skipping the first assignment. Is this a job for volatile? or is there a better solution…
Note: this is legacy api code, so I don’t plan of refactoring much. I am looking for a ‘local’ fix here.
Yes, just declare
wordAddressas a pointer tovolatiledata:The
volatilekeyword tells the compiler that the semantics have to match up with the abstract virtual machine specified by the C language — in other words, every time you write to avolatilevariable, the code has to actually write to memory, and every time you read from avolatilevariable, the code has to actually read from memory.The compiler is not allowed to optimize away these reads and writes, even if it thinks they are redundant.
Note that it must be the pointed-to data which is declared
volatile, not the pointer itself. Like theconstkeyword, it makes a big difference. SincewordAddressis itself a variable on the stack, we don’t care of reads/writes of it actually go out to the stack memory, but we do care that the memory it points to (presumably some type of memory-mapped I/O) is actually read/written.