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

printf("a");

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: http://www.ciselant.de/projects/gcc_printf/gcc_printf.html

If I’m printing two characters:

printf("ab");

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:

-fno-builtin

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 🙂

Advertisements

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

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

What do you think?

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

WordPress.com Logo

You are commenting using your WordPress.com 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