Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C99 inline function in .c file

Tags:

c

c99

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?

like image 422
user14416 Avatar asked Apr 26 '13 21:04

user14416


People also ask

Is inline supported in C?

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.

Can we extern inline function in C?

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.

What is __ inline in C?

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.

When was inline added to C?

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.


1 Answers

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.

like image 175
Jens Gustedt Avatar answered Nov 04 '22 06:11

Jens Gustedt