GNU gcc printf() and BuiltIn Optimizations

Readers of my blog know: I’m not a fan of printf(), and I think for many good reasons. Still printf() is widely used, and the GNU gcc tries to optimize things. This is observed with a simple example: If I’m writing


Then the code produced (ARM Cortex-M0+ with GNU ARM Embedded 4.9 2015q2 gives:

movs r0, #97    ; 0x61
bl 0xa98

Instead of calling printf(), it is calling putchar()! Why is that?

PutChar instead of Printf

PutChar instead of Printf

The reason is that the gcc compiler tries to optimize things as much as possible. In case of using printf() for a single character, it replaces it with a call to putchar() wich is much more efficient and smaller.

The following articles describes many of the optimizations performed by gcc:

If I’m printing two characters:


than gcc will use printf():

ldr r3, [pc, #8]        ; (0x62c <main+24>)
adds r0, r3, #0
bl 0xa64

So depending on what the compiler is able to optimize, other low-level functions will be used. If using semihosting or custom low-level I/O libraries that might cause linker error with missing functions.

To disable that compiler optimization, use the following compiler option:


If using the GNU ARM Eclipse plugins, there is a check box for that option in the project settings:

Disable Builtin Function Optimization

Disable Builtin Function Optimization

with that option set, printf("a") will use printf():

ldr r3, [pc, #16]       ; (0x630 <main+28>)
adds r0, r3, #0
bl 0xa6c

Happy Optimizing 🙂

7 thoughts on “GNU gcc printf() and BuiltIn Optimizations

  1. Pingback: Semihosting (again!) with NXP Kinetis SDK V2.0 | MCU on Eclipse

  2. Pingback: assert(), __FILE__, Path and other cool GNU gcc Tricks to be aware of | MCU on Eclipse

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 )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.