How will i know whether inline function is actually replaced at the place where it is called or not?

前端 未结 10 757
长发绾君心
长发绾君心 2020-11-27 16:17

I know that inline function are either replaced where it is called or behave as a normal function.

But how will I know whether inline function is actually replaced a

相关标签:
10条回答
  • 2020-11-27 17:15
    1. see the size of object files, they are different between inlined and not inlined
    2. use nm "obj_file" | grep "fun_name", they are also different
    3. gcc -Winline -O1
    4. compare with assembly code
    0 讨论(0)
  • 2020-11-27 17:17

    If you need to make sure that function is inlined and OK to go with proprietary extension in MS VC++, check out the __forceinline declarator. The compiler will either inline the function or, if it falls into the list of documented special cases, you will get a warning - so you will know the inlining status.

    Not endorsing it in any way.

    0 讨论(0)
  • 2020-11-27 17:20

    The decision to inline or not a function is made by compiler. And since it is made by compiler, so YES, it can be made at compile time only.

    So, if you can see the assembly code by using -S option (with gcc -S produces assembly code), you can see whether your function has been inlined or not.

    0 讨论(0)
  • 2020-11-27 17:20

    There is a way to determine if a function is inline programmatically, without looking at the assembly code. This answer is taken from here.

    Say you want to check if a specific call is inlined. You would go about like this. Compiler inlines functions, but for those functions that are exported (and almost all function are exported) it needs to maintain a non-inlined addressable function code that can be called from the outside world.

    To check if your function my_function is inlined, you need to compare the my_function function pointer (which is not inlined) to the current value of the PC. Here is how I did it in my environment (GCC 7, x86_64):

    void * __attribute__((noinline)) get_pc () { return _builtin_return_address(0); }
    
    void my_function() {
        void* pc = get_pc();
        asm volatile("": : :"memory");
        printf("Function pointer = %p, current pc = %p\n", &my_function, pc);
    }
    void main() {
        my_function();
    }
    

    If a function is not inlined, difference between the current value of the PC and value of the function pointer should small, otherwise it will be larger. On my system, when my_function is not inlined I get the following output:

    Function pointer = 0x55fc17902500, pc = 0x55fc1790257b
    

    If the function is inlined, I get:

    Function pointer = 0x55ddcffc6560, pc = 0x55ddcffc4c6a
    

    For the non-inlined version difference is 0x7b and for the inlined version difference is 0x181f.

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