1
votes

I don't understand why this is not possible :

inline void f(void) {}

int main(void)
{
    f();
}

Answer from extern inline:

C99 (or GNU99):

"inline": like GNU "extern inline"; no externally visible function is emitted, but one might be called and so must exist

Question 1:

What I understood is that f() is not externally visible , for me externally visible means that I can't call f() from another file , but here I'm calling it directly in main.What's the problem?

Solution

to put the definition in the .h file.

inline void f(void) {}

and the declaration in only one .c file

extern inline void f(void); 

Question 2 :

But I could also do :

this declaration goes in the header file

extern inline void f(void);

and this definition goes only in one .c file

extern void f(void) {}

and now I can use the function how I want , only condition is not to write

extern void f(void) {}

in any other .c file.

What are the risk if I don't use the "normal" solution , and do like I just wrote ?

compiled with

gcc -std=c11

1
Is there a reason you don't want to use static? - rici
Answer to #1: yes, that's how you do it. Answer to #2: no, don't do that. extern inline void f(void); makes no sense in a header file. - Dietrich Epp
@DietrichEpp I am trying to understand why it doesn't make sens , what's wrong with that ? how is it different from the right solution , could you explain please ? thanks - Oleg
@Oleg, did you see my answer? - Jens Gustedt

1 Answers

-1
votes

The inline keyword is there to allow you to make the definition of the function visible in all translation units, TU, (.c files) without causing an "multiple defined symbol" error. If you think of that purpose, having an inline definition in just one .c file and and referring to it in all others via a header declaration makes not much sense. In that case, just leave out the inline it serves no purpose. (And an extern inline declaration in a header makes even less sense.)

For the case that is foreseen, an inline definition in a header file avoids in any translation unit that the symbol is generated. So these different translation units can not be in conflict with each other. This strategy as an obvious limit, when your code actually needs the symbol. This can e.g be the case if you take the address of the function, or if the compiler decides for whatever reason that he can't or wouldn't use the definition of the function "in line". Therefore you always should tell the compiler in which TU you want to emit the symbol.