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
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.
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.
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
.