Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

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

Cisco IoT makes digital transformation a reality in factories, transportation, and utilities. Learn how to start integrating with Cisco DevNet.

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

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

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

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

Happy optimizing. :-)

Cisco is a software company. Surprised? Don’t be. Join DevNet to explore APIs, tools, and techniques that developers are using to add collaboration, IoT, security, network priority, and more!

Topics:
iot ,arm ,java

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

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}