Forcing/Checking Kinetis Compiler Optimization Level

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
  #error "unhandled compiler?"

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:

gcc Optimization Levels

gcc Optimization Levels

#if defined(__GNUC__)
  #if defined(__OPTIMIZED_SIZE__)
     /* -Os set */
  #elif defined(__OPTIMIZE__)
     /* -O1, -O2 or -O3 set */
     /* -O0 set */
#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 */
  #error "unhandled compiler?"

Happy Optimizing 🙂

What do you think?

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s