Loading lessons...
Inline Functions and Inline Variables
Inline Functions and Inline Variables
In modern C++, inline no longer just means "expand this code here". It now means: this definition may appear in many files - and they'll still be treated as one.
The old idea
Originally, inline asked the compiler to expand a small function's code at the call site, avoiding a call. Compilers now decide that for themselves, so the performance hint is mostly history.
The modern meaning
inline gives a function (or variable) external linkage while allowing the same definition in many files. That solves a classic problem: a function defined in a header.
// math.h - included by many .cpp files
inline int square(int x) { return x * x; }
Without inline, every file that includes math.h would define square, and the linker would complain about a duplicate. With inline, all those identical definitions collapse into one.
Inline variables (C++17)
Before C++17, constants were painful: put a definition in a header and you got linker errors; put it in one .cpp and other files couldn't see it. inline variables fix that:
// constants.h
inline const double PI = 3.14159; // C++17
inline int MAX_SIZE = 100;
Now a single shared object is created even though the header is included in many files.
Why use inline variables for globals across files
- Define a global once in a header, include it anywhere.
- No duplicate-definition linker errors.
- The whole program shares one object, not several copies.
TL;DR
inlinelets the same definition exist in many files as one entity.- The performance "expand here" meaning is secondary in modern C++.
- Put
inlinefunctions in headers and include them anywhere. inlinevariables (C++17) share one global across files.- Use them for constants and shared state defined in headers.