I keep hearing that the inline keyword is not useful as a hint for modern compiler anymore but is used to avoid the multiple definition error in the multi-source project.
But today I encountered an example that compiler obeys the keyword.
Without inline keyword, the following code
#include <iostream>
using namespace std;
void func(const int x){
if(x > 3)
cout << "HAHA\n";
else
cout << "KKK\n";
}
int main(){
func(5);
}
with the command g++ -O3 -S a.cpp, generates the assembly code with the func is not inlined.
However if I add inline keyword in front of the definition of func, the func is inlined into main.
The part of the generated assembly code is
.LC0:
.string "HAHA\n"
.LC1:
.string "KKK\n"
.text
.p2align 4,,15
.globl _Z4funci
.type _Z4funci, @function
_Z4funci:
.LFB975:
.cfi_startproc
cmpl $3, %edi
jg .L6
movl $4, %edx
movl $.LC1, %esi
movl $_ZSt4cout, %edi
jmp _ZSt16__ostream_insertIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_PKS3_l
.p2align 4,,10
.p2align 3
main:
.LFB976:
.cfi_startproc
subq $8, %rsp
.cfi_def_cfa_offset 16
movl $5, %edi
call _Z4funci
xorl %eax, %eax
addq $8, %rsp
.cfi_def_cfa_offset 8
ret
.cfi_endproc
My compiler is gcc 4.8.1 / x86-64.
I suspect that the function can be inlined during the linking process but I am not sure that will happen and if so, how can I know?
My question is why this code snippet seems to be contradictory to the modern guideline such as When should I write the keyword 'inline' for a function/method?
inlinemight influence the decision whether to inline, not that it's better in any way.staticdeclaration or-fltoflag.-fwhole-programor-flto) changes that, as does giving the function internal linkage (anonymous namespace). In the original case, once the compiler has produced the external function body, it considers it more expedient to call that function rather than duplicate the code in the main function.