In C++, inline functions were introduced to reduce the overhead of function calls. When a function is declared inline, the compiler attempts to replace the function call with the function's body, thereby avoiding additional costs associated with function calls, such as stack adjustments and jump instructions. However, whether the function is actually inlined depends on the compiler's optimization strategy and the function's complexity. Inline functions are primarily categorized as follows:
1. Regular Inline Functions
Regular inline functions are indicated by adding the inline keyword before the function declaration or definition, prompting the compiler to consider inlining the function. For example:
cppinline int add(int a, int b) { return a + b; }
This is the most straightforward application of inline functions, where the compiler will attempt to replace calls to this function with the function body directly.
2. Static Inline Functions
Static inline functions are defined with both static and inline keywords. These functions have a local copy in each file where they are defined, but they can still be inlined. For example:
cppstatic inline int max(int x, int y) { return x > y ? x : y; }
This approach ensures that the function is visible only within the file where it is defined, avoiding multiple definition issues across translation units (One Definition Rule).
3. External Inline Functions
External inline functions typically use the inline keyword and share the same definition across multiple files. To allow multiple files to link to the same function, a definition is provided in one file, and declarations are made in other files, typically using the extern keyword. For example, in a header file:
cppinline int min(int x, int y);
And in a source file:
cppinline int min(int x, int y) { return x < y ? x : y; }
This allows a single definition of the function to be shared across multiple files, and it may be inlined where called.
Summary
The main difference among them lies in their linkage and visibility. Regular inline functions and external inline functions can be shared across multiple files, whereas static inline functions are limited to the file in which they are defined. Furthermore, external inline functions require stricter management of declarations and definitions to ensure correct linkage, while regular inline functions and static inline functions are relatively simpler. When choosing which type of inline function to use, consider the function's scope, reusability, and the design of translation units.