gcc - When can/will a function be inlined in C++? Can inline behavior be forced? -


i trying expected behavior when use keyword inline. tried calling function in different files, templating function, using different implementation of inline function, whatever do, compiler never inlining function.

so in case compiler chose inline function in c++ ?

here code have tried :

inline auto add(int i) -> int {   return i+1; }  int main() {     add(1);     return 0; } 

in case, get:

add(int):     pushq   %rbp     movq    %rsp, %rbp     movl    %edi, -4(%rbp)     movl    -4(%rbp), %eax     addl    $1, %eax     popq    %rbp     ret main:     pushq   %rbp     movq    %rsp, %rbp     movl    $1, %edi     call    add(int)     movl    $0, %eax     popq    %rbp     ret 

or again,

template<typename t> inline auto add(const t &i) -> decltype(i+1) {   return i+1; }  int main() {     add(1);     return 0; } 

and got:

main:     pushq   %rbp     movq    %rsp, %rbp     subq    $16, %rsp     movl    $1, -4(%rbp)     leaq    -4(%rbp), %rax     movq    %rax, %rdi     call    decltype ({parm#1}+(1)) add<int>(int const&)     movl    $0, %eax     leave     ret decltype ({parm#1}+(1)) add<int>(int const&):     pushq   %rbp     movq    %rsp, %rbp     movq    %rdi, -8(%rbp)     movq    -8(%rbp), %rax     movl    (%rax), %eax     addl    $1, %eax     popq    %rbp     ret 

i used https://gcc.godbolt.org/ assembly code here, tried on machine clang , gcc (with , without optimization options).

edit:

ok, missing optimization options. if set gcc use o3 optimization level, method inlined.

but still. how gcc, or compiler, know when better inline function or not ?

as rule, code always inlined if specify:

__attribute__((always_inline)) 

eg (from gcc documentation):

inline void foo (const char) __attribute__((always_inline)); 

though never idea force compiler inline code.

you may set high optimization level (though o flag) achieve maximum inlining, more details please see gcc documentation

inlining controlled number of parameters. can set them using -finline-* options. can have @ them here


Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

php - Find a regex to take part of Email -

javascript - Function overwritting -