I have a working application but when I change the optimisation level my program behaves differently, what could be going on?
Changing the optimisation level can alter memory layout or application timing and the way that code is compiled!
One of the most valuable concepts in embedded programming is that of volatility. If you don't use the volatile keyword on your data, you're sure to come unstuck when you compile in release mode or with optimizations enabled. The most common form of this is waiting for an event to happen, such as a test on a counter or a flag, where the counter or flag has not been delcared volatile. In this case your code will run in Debug mode but not in Release mode.
- Remember to correctly declare objects that can be modified asynchronously as volatile. That is, declare global flags and counters as volatile, declare ring buffer pointers in structures as volatile, and certainly declare any GPIO or special register as volatile.
Changing the optimisation level will alter the memory layout, it may use more or less memory.
Common problems caused by change of memory layout are:
- Insufficient stack allocated - if the program is using more memory it is possible that the amount of memory allocated from the stack could exceed that allocated to it.
- Insufficient heap allocated - if the program is using more memory it is possible that the amount of memory allocated from the heap may exceed that allocated to it.
- Highlighting an existing bug - as the memory layout changes it may make the behaviour of an existing bug change or be more visible. For example, if the program is corrupting a particular area of memory, the area of memory being corrupted may be more or less important as the memory layout changes - in one memory layout it maybe an area of unused RAM in another it may be the stack.
Altered application timing
Changing the optimisation level may produce slower or faster code. If there is a time-related bug in the program such as a race condition the behavior of the program may change with different optimization levels.