You are about to hand over the firmware, and the board hangs with the Release build. Debug worked a moment ago. Git shows no new code changes. Turn optimization off, and it works again. Sending the working binary is tempting, but someone will eventually ask why it works.
Consider a short loop waiting for hardware to become ready. It reads a status register, a value representing the hardware’s state, and waits while the ready bit is zero. A one should end the wait. Yet the hardware can set that bit and leave the program spinning. A loop that keeps waiting is not necessarily a loop that keeps reading.
In this example, the pointer describes the register as ordinary memory. Nothing in the loop changes it. The compiler can conclude that another read is unnecessary and leave only the first one in the optimized code. If that read returns zero, later changes in the hardware never get a chance to end the wait.
The useful evidence is in the generated reads. In our illustrative x86-64 GCC 14.3 example, the unoptimized loop reads repeatedly; the optimized version reads once, then enters a loop with no further reads. This is a compiler example, not a measurement from a physical board. For your firmware, inspect the target’s assembly, the compiled instructions, and check whether the repeating part still reads the status register.
Start the fix with the chip documentation and its supplied register definitions. Arm CMSIS, for example, defines access qualifiers for peripheral registers. In this example, the pointed-to value needs to be volatile so each pass performs a read. Qualifying only the pointer variable is different. For the actual device, also follow its required access functions, read width, and any documented effects of reading the register.
That does not make volatile a fix for every Release failure. As the GCC documentation explains, it does not order ordinary memory accesses; it also does not provide thread synchronization or resolve data races. If the loop already rereads the status correctly, investigate other causes, such as timing, uninitialized values, or invalid memory access.
After correcting the access, rebuild with the Release settings you intend to ship and check that the wait ends on the same board with the same inputs. Keep the build options and the before-and-after reads with your notes. Working with optimization disabled is a useful clue. Evidence of a fix means the required reads are back and the intended build actually works.
Loading comments.