GNU gcc printf() and BuiltIn Optimizations

DZone 's Guide to

GNU gcc printf() and BuiltIn Optimizations

Why using putchar instead of printf is more efficient when using GNU ARM Embedded and Eclipse for IoT apps.

· IoT Zone ·
Free Resource

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

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:


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

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

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

Happy optimizing. :-)

arm, iot, java

Published at DZone with permission of Erich Styger , DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}