ProgrammingC++ Developer / Systems Programmer

What are inline functions in C++, how does the inline keyword work? What are the actual limitations and risks of excessive use of inline functions in large builds?

Pass interviews with Hintsage AI assistant

Answer.

Inline functions are functions for which the compiler may (but is not obligated to) replace the call with the direct insertion of the function's code at the call site. This is done using the inline keyword.

  • The inline keyword gives the compiler advice, but not an obligation: it can be ignored if the function is too complex.
  • In reality, functions defined within a class are considered inline by default.
  • Inline functions are often used for short, frequently called functions to avoid the overhead of calls.

Limitations and risks:

  • Frequent code duplication due to a large number of calls and inclusion of the same header function in different files can significantly increase the size of the binary.
  • Complex functions or functions that call other inline functions may not be inlined by the compiler.

Example:

inline int add(int a, int b) { return a + b; } struct X { int get() const { return value; } int value; }; // get() will be treated as inline

Trick question.

Question: Does the inline keyword guarantee that the function will be inlined at all call sites?

Answer: No. The compiler makes the decision to inline the function based on its internal heuristics. inline is only a recommendation.

Examples of real errors due to ignorance of the nuances of the topic.


Story

In a financial system, a frequently used logger was written with dozens of large inline functions. After the system grew, the size of the binary increased several times, leading to longer linking times and reduced caching efficiency on the server.


Story

During the migration of cross-platform software, it was discovered that some compilers (such as MSVC and GCC) handle inline differently: some functions were not inlined, while others were, causing hard-to-reproduce differences in speed and size of applications between platforms.


Story

The developer declared inline functions only in the header file but implemented them in a separate cpp file. As a result, linking errors occurred for multiple definitions or unresolved externals, as inline functions must be defined in headers.