There is such code:
int fun1(){
return 2 + 3;
}
inline int fun2(){
return 4 + 5;
}
int main(){
int a = fun1();
int b = fun2();
return 0;
}
and corresponding assembly code:
.file "prog47.cpp"
.text
.globl _Z4fun1v
.type _Z4fun1v, @function
_Z4fun1v:
.LFB0:
.cfi_startproc
.cfi_personality 0x0,__gxx_personality_v0
pushl %ebp
.cfi_def_cfa_offset 8
movl %esp, %ebp
.cfi_offset 5, -8
.cfi_def_cfa_register 5
movl $5, %eax
popl %ebp
ret
.cfi_endproc
.LFE0:
.size _Z4fun1v, .-_Z4fun1v
.section .text._Z4fun2v,"axG",@progbits,_Z4fun2v,comdat
.weak _Z4fun2v
.type _Z4fun2v, @function
_Z4fun2v:
.LFB1:
.cfi_startproc
.cfi_personality 0x0,__gxx_personality_v0
pushl %ebp
.cfi_def_cfa_offset 8
movl %esp, %ebp
.cfi_offset 5, -8
.cfi_def_cfa_register 5
movl $9, %eax
popl %ebp
ret
.cfi_endproc
.LFE1:
.size _Z4fun2v, .-_Z4fun2v
.text
.globl main
.type main, @function
main:
.LFB2:
.cfi_startproc
.cfi_personality 0x0,__gxx_personality_v0
pushl %ebp
.cfi_def_cfa_offset 8
movl %esp, %ebp
.cfi_offset 5, -8
.cfi_def_cfa_register 5
andl $-16, %esp
subl $16, %esp
call _Z4fun1v
movl %eax, 12(%esp)
call _Z4fun2v # why fun2 is called?
movl %eax, 8(%esp)
movl $0, %eax
leave
ret
.cfi_endproc
.LFE2:
.size main, .-main
.section .note.GNU-stack,"",@progbits
Why function fun2 is not inlined and called like normal function? I have read that inline keyword is only hint for compiler and it doesn't have to inline function, however definition of fun2 is so simple, so it could be inlined. How to force g++ to inline functions?
A function containing static variables cannot be made an inline function.
GCC automatically inlines member functions defined within the class body of C++ programs even if they are not explicitly declared inline . (You can override this with -fno-default-inline ; see Options Controlling C++ Dialect.)
When we should avoid the use of inline? We should not use functions that are I/O bound as inline functions. When large code is used in some function, then we should avoid the inline. When recursion is used, inline function may not work properly.
Specifies that a C function is to be inlined, or that a C or C++ function is not to be inlined.
Turn on optimizations. This is what you get for the main
function with -O2
(x86_64):
0000000000400560 <main>:
400560: 31 c0 xor %eax,%eax
400562: c3 retq
It's not only inline, it's removed.
Without optimizations, the compiler is much less likely to inline. (Inlining makes the code harder to debug, so having only very moderate levels of inlining with default non-optimizing options is a good idea.)
GCC has an attribute which forces inlining: always_inline
inline int fun2() __attribute__((always_inline));
inline int fun2() {
return 4 + 5;
}
Will cause it to work on any optimization settings.
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