I defined my function in .c (without header declaration) as here:
inline int func(int i) { return i+1; }
Then in the same file below I use it:
... i = func(i);
And during the linking I got "undefined reference to 'func'". Why?
Standard support C++ and C99, but not its predecessors K&R C and C89, have support for inline functions, though with different semantics. In both cases, inline does not force inlining; the compiler is free to choose not to inline the function at all, or only in some cases.
c file sees an extern declaration (without inline ) and an inline definition. Thus it emits the symbol for the function in the object file. All other compilation units only see an extern declaration, and so they can use the function without problems, if you link your final executable with the other .o file.
The __inline keyword suggests to the compiler that it compiles a C or C++ function inline, if it is sensible to do so. The semantics of __inline are exactly the same as those of the inline keyword.
Introduction. GNU C (and some other compilers) had inline functions long before standard C introduced them (in the 1999 standard); this page summarizes the rules they use, and makes some suggestions as to how to actually use inline functions.
The inline
model in C99 is a bit different than most people think, and in particular different from the one used by C++
inline
is only a hint such that the compiler doesn't complain about doubly defined symbols. It doesn't guarantee that a function is inlined, nor actually that a symbol is generated, if it is needed. To force the generation of a symbol you'd have to add a sort of instantiation after the inline
definition:
int func(int i);
Usually you'd have the inline
definition in a header file, that is then included in several .c files (compilation units). And you'd only have the above line in exactly one of the compilation units. You probably only see the problem that you have because you are not using optimization for your compiler run.
So, your use case of having the inline
in the .c file doesn't make much sense, better just use static
for that, even an additional inline
doesn't buy you much.
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