2

I noticed that GCC is very smart about optimizing printf. For example, printf("") is completely removed from the resulting code. printf("\n") is replaced with putchar('\n').

I noticed when I compile a very small module like this:

extern "C" int printf(const char *__restrict __format, ...); void f() { printf("\n"); } 

with gcc -O2 the call to printf is replaced with putchar('\n') (don't even need to include any header files).

Generated code:

f(): mov edi, 10 jmp putchar 

What is the mechanism that allows those optimizations to be performed? As far as I know standard C++ does not provide any features that allows such optimizations.

Could it be extended for the user functions or is it "hardcoded" in the compiler?

This also means if I wanted to redefine printf with my own implementation the compiler might mess it up. Is it true?

1 Answer 1

1

When compiling with GCC certain functions are built-in functions. That means that their implementation is built into the compiler and the library version is ignored. printf is one such function.

Take a look at http://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the link. Unfortunately it doesn't describe all the possible optimizations that might happen. Just lists the functions.
Once a function is in the compiler, the compiler is free to provide any code substitution that exhibits the same behaviour. In the case of printf, it can examine the format string and generate code accordingly. A library function cannot do this.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.