When can a / function be included in C ++? Can coercive behavior?

I am trying to get the expected behavior when I use a keyword inline

. I tried to call the function in different files, templating the function using different inline function implementation, but no matter what I do, the compiler never inlines the function.

So in which case exactly would the compiler choose a built-in function in C ++?

Here is the code I tried:

inline auto Add(int i) -> int {
  return i+1;
}

int main() {  
  Add(1);  
  return 0;
}

      

In this case, I 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 I 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/ to get the build code here, but I also tried on my machine with clang and gcc (with and without optimization options).

EDIT:

Ok, I am missing something with the optimization options. If I configure GCC to use the o3 optimization layer, my method is inlined .

But still. How does GCC or another compiler know when to inline a function or not?

+3


source to share


2 answers


Typically, your code is always inlined only if you specify:

__attribute__((always_inline))

      

for example (from gcc documentation):

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

      



Though it's almost never a good idea to force your compiler to inline your code.

You can set the optimization level to a high (although the O flag) to achieve maximum insertion, but see the gcc documentation for more information

Nesting is actually controlled by a number of parameters. You can install them using the -finline- * options. You can see them here

+6


source


By the way, you didn't actually declare the function. You have declared a functor, an object that can be called but can also persist state. Instead of using the syntax:
  inline auto Add (int i) β†’ int {



you want to say simply:
  inline int Add (int i) {

0


source







All Articles