Modify Arduino Optimization Levels on the Fly


Do you know and understand how compiler optimization is altering your code? Higher optimization levels can reveal problems in some programs that are not apparent at lower optimization levels.


One method to prevent optimization issues with variables is to declare them as volatile. The declaration of a variable as volatile tells the compiler that the variable can be modified at any time externally to the implementation, for example, by the operating system, by an interrupt handler, or by hardware. Because the value of a volatile-qualified variable can change at any time, the actual variable in memory must always be accessed whenever its referenced in code. This means the compiler cannot perform optimizations on the variable.

Arduino defines the volatile keyword on this webpage using the following example. However, this code neglects to access the 2-byte variable, state atomically. This code probably will survive because the variable, being a 2-byte integer, only uses the lower byte. See the first example on this page for further information.

Arduino Example:

// toggles LED when interrupt pin changes state
int pin = 13;
volatile int state = LOW;

void setup() {
pinMode(pin, OUTPUT);
attachInterrupt(0, blink, CHANGE);

void loop() {
digitalWrite(pin, state);

void blink() {
state = !state;


Another method is to compare versions of your code with different levels of optimization. You may not realize that changing the optimization level of your code is actually very easy once you know how. Here are two techniques to change the optimization level on the fly.

Pragma-tic Programming

To change optimization for large areas of code, I recommend using the optimize pragma. Surrounding the code with the push and pop option pragma is also a good practice. Here is an example:

#pragma GCC optimize ("-O0")
#pragma GCC push_options

void setup() { }
void loop() { }

#pragma GCC pop_options

Know Your Attributes

If you want to effect the optimization of just a single function, use the optimize attribute like so:

void loop() __attribute__((optimize("-O0")));
void loop() { }


More information on GCC optimization can be found here.
More information on GCC function attributes can be found here.
More information on GCC pragmas can be found here.

About Jim Eli

µC experimenter
This entry was posted in arduino, avr and tagged , , , . Bookmark the permalink.

1 Response to Modify Arduino Optimization Levels on the Fly

  1. Pingback: Optimizarea programelor în mediul Arduino IDE | Robofun Blog

Leave a Reply

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

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

Google photo

You are commenting using your Google 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 )

Connecting to %s