Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C, should inline be used in definition or declaration [duplicate]

Tags:

c

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?

like image 730
Josh Avatar asked Sep 07 '25 09:09

Josh


1 Answers

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 ints 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;
}
like image 71
0___________ Avatar answered Sep 10 '25 02:09

0___________