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

前端 未结 10 761
长发绾君心
长发绾君心 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: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.

提交回复
热议问题