1

Following these two links: Should C declarations match definition including keywords and qualifiers such as "static", "inline", etc

and

https://www.greenend.org.uk/rjk/tech/inline.html

They say the following is the way to use inline functions in C:

a.c

#include <stdio.h>

inline int add(int a , int b){
 return a+b;
}

int main(){
 printf("%d\n", add(1,2));
 return 0;
}

b.c

int add(int a , int b);

inline int add(int a , int b){
 return a+b;
}

Then compile with: gcc a.c b.c.

Now here is my confusion:

Why does adding a declaration of int add(int a , int b); to b.c cause a symbol generation? I thought only function definitions create symbols in a translation unit not their declarations. Why is this backwards? Is inline a special case?

It's really wired that I have to have an external symbol to work with inline functions. Why can't C compile a.c on it's own! (I know gnu89 and C++ do, wondering why c99 was coded like this to begin with).

Josh
  • 67
  • 2
  • `b.c` contains both a declaration and a definition. – Barmar Jun 15 '20 at 22:39
  • It doesn't tho, `inline` declaration doesn't emit any symbol technically. – Josh Jun 15 '20 at 22:41
  • `inline` functions don't emit a symbol unless they're also declared `extern`. – Barmar Jun 15 '20 at 22:42
  • @Barmar Ok so why does the `declaration` in `b.c` cause a symbol generation? this is weird and not like other C practices. – Josh Jun 15 '20 at 22:44
  • I see your point, I'm not sure – Barmar Jun 15 '20 at 22:46
  • `a.c` works by itself if it's `static inline` or `extern inline`. – Barmar Jun 15 '20 at 22:46
  • If the answers in the other question weren't adequate, you should clarify that question, not post an almost identical question. – Barmar Jun 15 '20 at 22:54
  • No it's not covered. I'm asking why the behaviour of definition vs declaration is backwards here. Why doesn't every `declaration` in a header file cause symbol generation then? – Josh Jun 15 '20 at 22:54
  • definition is not inline then it is extern by default. You say the compiler to emit the non inline version of the function. The function can be also inlined if the compiler decides to do so asd the optimizations are enabled. Without the optimisations `inline`is ignored and if both definition and declaration are `inline` the program will not link. https://godbolt.org/z/yQj3jC – 0___________ Jun 15 '20 at 23:00

0 Answers0