Skip to content
Tutorials Center
My learning

Topics

Lesson 46 of 171 ยท Functions

inline Functions

What inline really means in modern C++ - the one-definition rule, defining functions and variables in headers, implicit inline, C++17 inline variables, and optimizer inlining.

The keyword inline has one of the most misunderstood meanings in C++. Most people learn that it asks the compiler to "paste the function body where it's called, to make the program faster". That was the original idea in the 1980s, and the optimization it describes, inlining, is still very real. But the keyword inline no longer controls it in any meaningful way. Today, inline means something different and more useful: "this definition may appear in several source files, and they are all the same thing."

That makes inline the tool for putting function and variable definitions in header files. In this lesson you'll learn what inlining is and who decides it, what the inline keyword actually guarantees, which functions are inline without the keyword, how C++17 inline variables fixed a long-standing headache with constants, and when you should write inline yourself. You'll use the one-definition rule (ODR) a lot here; Header Files and Multiple Source Files covers it from the build-system side.

Inlining: the optimization

Calling a function has a small cost: arguments are placed in registers or on the stack, the CPU jumps to the function, and then jumps back. For a tiny function like square(x), that overhead can be bigger than the work itself. Inlining replaces the call with a copy of the function's body, so square(n) + 1 becomes n * n + 1 in the generated machine code.

Inlining is valuable mainly because of what it enables next. Once the body is visible at the call site, the optimizer can fold constants, delete dead branches and keep values in registers. A loop that calls a small accessor a million times can become a tight loop with no calls at all.

The decision is made by the optimizer, not by you. At -O1 and above, GCC and Clang inline small functions whether or not they're marked inline, and they're free to not inline a function marked inline if it's large, recursive, or called through a pointer. At -O0 (no optimization) they typically inline nothing.

C++ The optimizer inlines without being asked

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

You can't see the inlining in program output, which is exactly the point: inlining never changes what a correct program does, only how fast it runs. To see it, you'd look at the generated assembly, for example on Compiler Explorer (godbolt.org), which you'll meet in Compilers, Flags and Optimization.

GCC and Clang have non-standard attributes for the rare cases where you must override the optimizer: [[gnu::always_inline]] and [[gnu::noinline]] (MSVC: __forceinline and __declspec(noinline)). Use them only after measuring. Most programs never need them.

What the inline keyword really means

To understand the modern meaning, recall the one-definition rule (ODR):

  • A normal (non-inline) function or variable may be declared many times but defined exactly once in the whole program.
  • If two source files each define int square(int x) { ... }, the linker sees two symbols with the same name and stops with a "multiple definition" error.

That's a problem for headers. A header is pasted into every .cpp file that includes it, so a function defined in a header gets defined once per including file:

C++
// math_utils.h
#pragma once

int square(int x) {        // defined in the header, not inline
    return x * x;
}

If main.cpp and report.cpp both include this header, linking fails:

TEXT
/usr/bin/ld: report.o: in function `square(int)':
report.cpp:(.text+0x0): multiple definition of `square(int)'; main.o:main.cpp:(.text+0x0): first defined here
collect2: error: ld returned 1 exit status

Adding inline fixes it:

C++
// math_utils.h
#pragma once

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

An inline function:

  • may be defined in several translation units (source files after preprocessing), as long as every definition is identical, token for token, with the same meaning;
  • must be defined in every file that uses it (which a header guarantees automatically);
  • is still one function: it has a single address, and a static local variable inside it is shared by the whole program.

The linker keeps one copy of any out-of-line version and discards the duplicates. So "inline" is really about linkage and the ODR, and that's why it's the right tool for header-only code.

Identical means identical. If two files see different definitions of the same inline function, perhaps because a macro changed what the header expands to, the program violates the ODR. That's undefined behavior, and usually no tool tells you: the linker silently keeps one version, and some callers get the "wrong" function. Never let headers depend on macros that differ between files.

Functions that are inline automatically

You'll write the keyword less often than you might think, because several kinds of functions are implicitly inline:

Function Implicitly inline?
Member functions defined inside a class body Yes
constexpr functions Yes
consteval functions Yes
Function templates and members of class templates Not formally, but they have the same "define in every file" permission
Functions defined in a class body as friend Yes
Ordinary functions, members defined outside the class No

This is why a class defined entirely in a header just works:

C++ Implicitly inline member and constexpr functions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

In a single .cpp file, the inline on warm_by changes nothing you can observe. It matters the moment this code moves into a header shared by several files. That "it only breaks when the project grows" quality is what makes the rules worth learning now.

Inline variables (C++17)

Before C++17, sharing a single global object across files required a two-step dance: an extern declaration in the header and exactly one definition in some .cpp file. Static data members of classes needed the same treatment, which was a constant annoyance:

C++
// Old style, pre-C++17
// config.h
extern int max_connections;          // declaration only
// config.cpp
int max_connections = 100;           // the one definition

C++17 allows inline on variables. An inline variable can be defined in a header; every file sees the same single object:

C++
// config.h (C++17 and later)
#pragma once
#include <string>

inline int max_connections = 100;
inline const std::string app_name = "Inventory";

It's even more useful for static members, which can now be initialized right in the class:

C++ inline static members and a shared counter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

static constexpr data members are implicitly inline since C++17, so max_per_event needs no extra keyword. You'll learn more about static members in Static Members.

Constants in headers: constexpr vs inline constexpr

At namespace scope, a const or constexpr variable has internal linkage: each file that includes the header gets its own private copy. For a small number like constexpr int max_users = 64;, that's harmless, since the compiler usually folds the value into the code. But it means &max_users differs between files, and a large constant (a lookup table, a std::array of a thousand entries) may be duplicated in every object file.

Writing inline constexpr gives one shared object for the whole program:

C++
// limits.h
#pragma once
#include <array>

constexpr int max_users = 64;                       // a copy per file (fine for small values)
inline constexpr std::array<int, 4> tiers{1, 5, 25, 125};  // one object program-wide

The standard library itself declares many of its constants as inline constexpr, including std::numbers::pi (see Constants).

inline and static local variables

Because an inline function is a single function, a static local variable inside it exists once for the whole program, even though its definition appears in many files. That makes the function-local static a standard way to give a header-only library one shared object that's created on first use:

C++ One static object inside an inline function

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

If you'd marked these functions static instead of inline, every file would get its own private function and its own vector, and messages logged in one file would be invisible in another. That difference between inline (one shared entity) and static or an anonymous namespace (one private copy per file) is covered in Scope, Lifetime and Storage Duration and Namespaces.

When to write inline

Practical guidelines for modern C++:

  • Write inline for non-template functions defined in a header at namespace scope, and for member functions defined outside the class but still in the header.
  • Write inline for variables defined in headers that must be one shared object: inline globals, inline static members, inline constexpr tables.
  • Don't write inline on functions in a .cpp file hoping for speed. The optimizer already decides, and it knows more than the keyword. If a function should be private to that file, put it in an anonymous namespace instead.
  • Don't write it where it's already implied: in-class member definitions, constexpr functions, templates.
  • Keep header functions small. Every file that includes a header compiles its inline functions. Large bodies in headers slow down builds; move them into a .cpp file.

For real speed, enable optimization (-O2), consider link-time optimization (-flto), which lets the compiler inline across .cpp files, and measure. See Writing Fast C++.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In modern C++, what does the inline keyword primarily guarantee?

    Whether a call is actually inlined is the optimizer's decision. The keyword's real guarantee is about linkage. Identical definitions in several files are allowed and refer to one entity.
  2. 2. A non-inline function is defined in a header that two .cpp files include. What happens?

    Each translation unit defines the same external symbol, which violates the one-definition rule, so the linker reports "multiple definition".
  3. 3. Which of these functions is implicitly inline?

    Member functions defined inside the class body are implicitly inline, and so are constexpr functions. Members defined outside the class need the keyword if they live in a header.
  4. 4. A header contains inline int counter() { static int n = 0; return ++n; }. Two .cpp files each call it once. What does the second call return?

    An inline function is one function with one address, so its static local variable exists once for the whole program.
  5. 5. What did C++17 inline variables make possible?

    Before C++17, a shared global or static member needed an extern declaration plus one out-of-line definition. An inline variable can be defined in the header itself.

Summary

  • Inlining (replacing a call with the function body) is an optimization the compiler performs on its own, mainly at -O1 and above; the keyword neither forces nor prevents it.
  • The inline keyword means "identical definitions may appear in several files and are one entity", which makes it the tool for definitions in headers.
  • Without inline, a function defined in a header included by two files causes a multiple definition link error.
  • In-class member definitions, constexpr/consteval functions and templates are inline (or behave so) automatically.
  • C++17 inline variables allow shared globals and inline static members in headers; static constexpr members are implicitly inline. Use inline constexpr for big constants in headers.
  • An inline function has one address and one copy of each static local, unlike a static function, which is private to each file.

Next: Recursion, where functions call themselves to solve problems that contain smaller copies of themselves.