A friend wrote a function, about 300 lines of code, and asked me how to turn it to be inline.
I told him it's too big, and will result in instruction enflation. Then I thought, but he calls this function only once. So, there's no downside.
It feels wrong. Is it wrong?
Gcc does this optimization. When a static function is only called once it gets inlined. It doesn't do this with external functions because it can't determine who calls the function.
You can check the assembler by going here:
https://gcc.godbolt.org/
First with an extern function:
#include <stdio.h>
extern int test(int x);
int main() {
int x = test(10);
printf("%d\n", x);
}
int test(int x)
{
volatile int y = x;
for (int i = 0; i < 10; i++)
y++;
for (int i = 0; i < 10; i++)
y++;
return y;
}
The assembler output of main() with -O optimization as compiler flag:
main:
subq $8, %rsp
movl $10, %edi
call test(int)
movl %eax, %esi
movl $.LC0, %edi
movl $0, %eax
call printf
movl $0, %eax
addq $8, %rsp
ret
You can see that test is called and the return value in EAX is stored in $0.
Now make test static and observe that the call to test dissappears and the code is inlined.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With