What is the standard way to restrict the optimizing compiler to duplicate assignments?

I have built-in code that writes commands to a memory address for controlling a peripheral device like this:

void intelStartEraseBlock(uint16_t *wordAddress) { *wordAddress = 0x20; //block erase *wordAddress = 0xD0; //block erase confirm } 

I suspect the optimizer is skipping the first job. Is it work for unstable work? or is there a better solution ...

Note: this is deprecated api code, so I don't plan on much refactoring. I am looking for a local fix here.

+4
source share
3 answers

Yes, just declare wordAddress as a pointer to volatile data:

 void intelStartEraseBlock(volatile uint16_t *wordAddress) { ... } 

The volatile keyword tells the compiler that the semantics must match the abstract virtual machine defined by C - in other words, every time you write a volatile variable, the code must actually be written to memory, and every time you read the volatile variable, the code should really read from memory.

The compiler cannot optimize these reads and writes, even if it considers them redundant.

Note that this should be pointer data declared volatile , not the pointer itself. Like the const keyword, this matters a lot. Since wordAddress itself is a variable on the stack, we do not care that its read / write actually goes on the memory stack, but we do care that the memory it points to (presumably some type of display I / O memory) is actually read / write.

+6
source

That is why the volatile keyword was created. This is a classic use case.

+10
source

If your operating system does not provide any other mechanism to perform this kind of action, then yes, volatile is a good solution.

 void intelStartEraseBlock(volatile uint16_t *wordAddress) { *wordAddress = 0x20; //block erase *wordAddress = 0xD0; //block erase confirm } 
+2
source

All Articles