Sunday, 29 June 2014

Behavior of built-in functions in c/c++

GCC normally generates special code to handle certain built-in functions more efficiently; for instance, calls to "alloca" may become single instructions that adjust the stack directly, and calls to "memcpy" may become inline copy loops. The resulting code is often both smaller and faster, but since the function calls no longer appear as such, you cannot set a breakpoint on those calls, nor can you change the behavior of the functions by linking with a different library.
--- GCC doc
As per the above comment, GCC compiler internally links with different function body for same function call
Ex:

Ex:1
#include<stdio.h>

int main()
{
        int a=10;
        printf("Value of a:%d\n",a);
}
If you look into the object file for the above mentioned code, it contains two function signatures those are
00000000 T main
         U printf
 

Now consider the below mentioned code
Ex:2
#include<stdio.h>

int main()
{
        printf("Hello World!");
}

the object file for the above mentioned code will contains two function signatures those are
00000000 T main
         U puts

Note that, both example mentioned above use a function call printf, but the object code shows two different function signatures, those are printf and puts.
The above examples show that compiler use printf function internally when more than one parameter is passed in printf function, but same printf function is replaced by puts when it is called with one parameter.

GCC compiler also provide an option to disable this behavior if required, for example

If Ex:2 is compiled with -fno-builtin option then the object file will contain the signatures:
00000000 T main
         U printf

In this way compiler will not consider any built-in function for optimization, but what if only one function requires built-in function optimization.
Let see how to do this....
  • Define one macro with the same function name
  • prepend __builtin_ keyword with the function 
Example:

#include<stdio.h>
#define printf __builtin_printf
int main()
{
        int a=10;
        printf("Hello Wolrd!\n");
        printf("Value of a:%d\n",a);
}
This way compiler will always use builtin function optimization even if code is compiled with -fno-builtin.


No comments :

Post a Comment