As noted in my post on gcc and FreeRTOS, some code might be very sensitive to compiler optimizations. While porting code from the Freescale ARM/Kinetis compiler to the gcc compiler as in MCU10.3, I have found way how to force compiler optimization levels in my source code.
The idea is to use a #pragma as outlined in the gcc documentation. A similar approach is used for the Freescale ARM compiler.
Setting Compiler Optimization Level
Knowing that gcc defines the macro __GNUC__ and the Freescale compiler __CWCC__, I can enforce the optimization level with this source:
#if defined(__GNUC__)
#pragma GCC optimize ("O2")
#elif defined(__CWCC__)
#pragma optimization_level 2
#else
#error "unhandled compiler?"
#endif
Checking Compiler Optimization Level
With the following source I can check the compiler optimization level, as I use it in my FreeRTOS port.
GCC defines the macros __OPTIMIZE_SIZE__ if -Os is set, and __OPTIMIZE__ if any of the -O1, -O2 or -O3 option is set:
#if defined(__GNUC__)
#if defined(__OPTIMIZED_SIZE__)
/* -Os set */
#elif defined(__OPTIMIZE__)
/* -O1, -O2 or -O3 set */
#else
/* -O0 set */
#endif
#elif defined(__CWCC__)
#if defined(__optlevel0)
/* optimization level 0 */
#elif defined(__optlevel1)
/* optimization level 1 */
#elif defined(__optlevel2)
/* optimization level 2 */
#elif defined(__optlevel3)
/* optimization level 3 */
#elif defined(__optlevel4)
/* optimization level 4 */
#endif
#else
#error "unhandled compiler?"
#endif
Happy Optimizing 🙂
