Here inline
is used in both definition and declaration which compiles successfully:
#include <stdio.h>
inline int add(int a , int b);
inline int add(int a , int b){
return a+b;
}
int main(){
printf("%d\n", add(1,2));
return 0;
}
It also compiles fine if we use inline in either definition OR declaration.
Which one is the correct way of doing it? is there a rule in C to explain it as there are similar rules for static
and extern
?
even the inline
needs a body. So if you only
inline int add(int a , int b);
you just inform the compiler that there is a function called add
taking two int
s as the parameters and returning int. You give the compiler a hint
that you would like this function to be inlined.
but what will actually happen depends on the implementation.
gcc will only link the program successfully if optimizations are enabled. If not compiler will not emit the not inlined version of the function and the linking will fail. https://godbolt.org/z/yQj3jC
To make sure that it will link in any circumstances you need to:
int add(int a , int b);
inline int add(int a , int b){
return a+b;
}
In this case yuo will have not inlined version of the function but compiler will inline it if it finds it necessary https://godbolt.org/z/2BDA7J
In this trivial example function will be inlined when optimizations are enabled even if there is no inline
keyword. https://godbolt.org/z/h3WALP
inline
is just the hint and compiler may choose to inline it or not. Some compilers have special mechanisms to force inlining
inline __attribute__((always_inline)) int add(int a , int b){
return a+b;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With