Consider the following C++-code with an inline-function:
// this function is in a header-file:
// recursion prevents inlining
inline int calc(int k){
if(k<=1) return 1;
return calc(k-1)+calc(k-2);
}
// this function is in a source-file:
int fun(int k){
return calc(k);
}
Here I use recursion, to simulate the case when compiler was not able to inline the function calc.
The resulting assembly (compiled with -Os, see live on https://godbolt.org/):
...
.weak calc(int)
.type calc(int), @function
calc(int):
// some assembler
.text
.globl fun(int)
.type fun(int), @function
fun(int):
...
jmp calc(int)
As expected, the compiler was not able to inline calc, and thus emitted code for it, but due to inline-keyword it becomes a weak symbol.
Compiling the same code as C, produces a different result (with -Os,see live on https://godbolt.org/):
.Ltext0:
.globl fun
.type fun, @function
fun:
...
jmp calc
The most notable difference: there is no code emitted for calc, so basically the linker will not able to link the executable, as the definition of calc is missing.
Obviously, inline means different things in C compared to C++.
What are differences for inline in C compared to C++? How the definition of calc should be done, that it can be used in a header in C and C++ at the same time?