This is because both variables are changing in an interrupts, unexpectedly for the compiler.
When I compiled my RTU port using BARE demo template, I discovered it works without an optimization and doesn't with high level.
The single failure point was portevent.c with variable definition. It is obvious that these variables need to be volatile to be processed correctly in MODBUS poll function.
Demo portevent.c variables are optimized-out by current compilers. No events received from a bus. Here, demo/BARE/port/portevent.c:
Both variables MUST be declared with volatile qualifier:
This is because both variables are changing in an interrupts, unexpectedly for the compiler. When I compiled my RTU port using BARE demo template, I discovered it works without an optimization and doesn't with high level. The single failure point was portevent.c with variable definition. It is obvious that these variables need to be volatile to be processed correctly in MODBUS poll function.