ProgrammingC/C++ Engineer

Tell us about the differences between functions declared as inline and regular functions in C. What are the limitations, how to properly declare inline functions when working with multiple source files, what mistakes do developers often make?

Pass interviews with Hintsage AI assistant

Answer

inline is a hint to the compiler to replace the function call with its body (code inlining). This can speed up execution (no call overhead), but it leads to an increase in the binary size.

Syntax:

inline int square(int x) { return x * x; }

The compiler may ignore inline. To have visibility and implementation of the function in different files simultaneously, use:

// header.h inline int min(int a, int b) { return a < b ? a : b; }

The entire body of the function must be accessible in every file where the inline function is called, i.e., the usual way is to define the function in a header file.

If you declare and define an inline function only in one .c file, other modules will not be able to use it, resulting in linker errors (undefined reference).

Trick Question

What is the difference between such declarations in the header file?

inline int foo(int x) { return x + 1; } static inline int bar(int x) { return x + 1; }

Answer:

  • inline int foo(...) allows the function to have multiple weak definitions (one definition rule). If the same header is included in several .c files, the linker may throw a multiple definition error.
  • static inline makes the function internal to each module: each link point gets its copy, so there will be no linking issues. This is the safest approach for inline functions in headers.

Examples of real errors due to unawareness of the nuances of the topic


Story

In a library of mathematical functions, many inline helpers were defined in a .c file. When trying to use them from other modules, linking errors occurred because the definitions were only visible in one object file.


Story

After moving inline functions from the .c file to the header, the project began to fail at the linking stage: the linker complained about multiple definitions of the same function. This was fixed by replacing it with static inline in the header files.


Story

In optimizing an internal algorithm, inline was used for "critical" functions, expecting a speed-up. However, the compiler ignored the hint, and the profiler showed that call costs did not decrease. The problem was resolved only after a manual analysis of compiler optimization options.