Is it possible to force a function not to be inlined?

前端 未结 9 582
攒了一身酷
攒了一身酷 2020-12-01 11:30

I want to force a little function not to be compiled as inline function even if it\'s very simple. I think this is useful for debug purpose. Is there any keyword to do this?

相关标签:
9条回答
  • 2020-12-01 12:19

    Many compilers can perform cross-translation-unit inlining. Visual Studio has had it for five years and I believe that GCC can now do it- especially since the OP tagged as Visual C++, it's a fair bet that his compiler can cope.

    The simplest way to do this is to take the function's address, and then do something non-meaningless with it, like call it or pass it to an OS/external library function. The compiler can't inline that kind of function.

    Why you would ever want to, IDK.

    @comments:

    If the OP srsly, srsly needs this, then he could compile it as a lib and statically link to it.

    0 讨论(0)
  • 2020-12-01 12:20

    [[gnu::noinline]] attribute

    We can also use the C++11 attribute specifier syntax with the non-standard gnu::noinline attribute: https://en.cppreference.com/w/cpp/language/attributes

    It is just a matter of time until that gnu:: part gets dropped a future C++ standard to give a standardized [[noinline]] :-)

    main.cpp

    [[gnu::noinline]]
    int my_func() {
        return 1;
    }
    
    int main() {
        return my_func();
    }
    

    Compile and disassemble:

    g++ -ggdb3 -O3 -o main.out -std=c++11 -Wall -Wextra -pedantic-errors main.cpp
    gdb -batch -ex 'disassemble/r main' main.out
    

    With [[gnu::noinline]]:

       0x0000000000001040 <+0>:     f3 0f 1e fa     endbr64 
       0x0000000000001044 <+4>:     e9 f7 00 00 00  jmpq   0x1140 <my_func()>
    
    

    Without [[gnu::noinline]]:

       0x0000000000001040 <+0>:     f3 0f 1e fa     endbr64 
       0x0000000000001044 <+4>:     b8 01 00 00 00  mov    $0x1,%eax
       0x0000000000001049 <+9>:     c3      retq
    

    Tested on Ubuntu 19.10.

    0 讨论(0)
  • 2020-12-01 12:28

    Is it possible to force a function not to be inlined?

    I won't even attempt to answer that question, because it's irrelevant to be concerned with this except for the two reasons outlined below.

    Inlining basically is

    1. an optimization that's mostly transparent to you
    2. a way to allow functions to be defined in headers without getting multpile definition errors

    (Some would switch the order of these two, but I stick to the traditional order.)

    Unless either A) you absolutely need to define a function in some header or B) you are profiling and optimizing a piece of code and know better than the compiler what should be inlined and what shouldn't, inlining should be of no concern to you.
    It certainly shouldn't be a concern because of debugging. Your debugger should (and in the case of VC also does) take care of that for you.

    0 讨论(0)
提交回复
热议问题