Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 135 ยท Functions

inline Functions

Learn what inline really means in C, why a plain inline function can fail to link, how static inline works in headers, and how C's rules differ from C++.

Calling a function costs a little: arguments are set up, the program jumps to the function, and it jumps back. For a tiny function like "square a number", that overhead can be larger than the work itself. Inlining removes it: the compiler copies the function's body straight into the caller, as if you'd written the code there by hand.

C99 added the inline keyword so you could write small helper functions in header files without paying for calls and without the bugs of macros. But inline in C is widely misunderstood. It doesn't force inlining, and a plain inline function in C follows linking rules that surprise people who know C++. In this lesson you'll learn what the keyword actually promises, why static inline is the form you'll use almost every time, and how the less common inline + extern combination works.

What inlining is, and who decides

Here is a function and a call to it:

C
static int square(int x)
{
    return x * x;
}

int area = square(side);

When the compiler inlines square, the call disappears and the generated code is simply area = side * side;. Besides saving the call, inlining often unlocks more optimization: if side is a known constant, the whole expression can be computed at compile time.

The important fact is that the compiler decides, not you. With optimization on (-O1, -O2, -O3), GCC and Clang inline small functions on their own, whether or not you write inline. With optimization off (-O0, the default for debug builds), they inline almost nothing. The inline keyword is only a suggestion that "calls to this function should be as fast as possible". Compilers are free to ignore it, and modern ones mostly do, trusting their own cost models instead.

So why does the keyword exist at all? Mainly for a different reason: to let you define a function in a header file that many source files include, without getting "multiple definition" errors at link time. That's where C's specific rules come in.

Why not just use a macro?

Before inline, small helpers were often written as function-like macros. Macros are pure text substitution, so they have no call overhead, but they also have no types and they evaluate their arguments as many times as the text mentions them. An inline function evaluates each argument exactly once and checks its types.

C A macro evaluates arguments twice

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 scanf or fgets), it gets the next line from this box.

The output shows the difference:

TEXT
macro:    result 20, calls to next_reading: 2
function: result 10, calls to next_reading: 1

The macro expands to ((5) > (next_reading()) ? (5) : (next_reading())). The first call returns 10, which is bigger than 5, so the macro calls next_reading() again and returns 20, a value that was never compared. The function gets each argument once and returns the reading it actually tested. With optimization on, both versions compile to equally fast code. Prefer static inline functions over macros for anything that behaves like a function; keep macros for the jobs only the preprocessor can do (see Macros).

static inline: the form to use

Mark a small helper static inline and you get the behavior most people expect from inline:

  • static gives the function internal linkage: each source file that includes the header gets its own private copy, so there's never a "multiple definition" conflict between files.
  • inline tells the compiler (and readers) that the function is meant to be small and fast.
  • If the compiler inlines every call, no copy of the function is emitted at all. If it decides not to (or you take the function's address), it emits a private copy in that file. Either way, the program links.

A typical header looks like this:

C
// vec2.h
#ifndef VEC2_H
#define VEC2_H

typedef struct {
    double x;
    double y;
} vec2;

static inline vec2 vec2_add(vec2 a, vec2 b)
{
    return (vec2){a.x + b.x, a.y + b.y};
}

static inline double vec2_dot(vec2 a, vec2 b)
{
    return a.x * b.x + a.y * b.y;
}

#endif

Every .c file that writes #include "vec2.h" can call these functions, and the optimizer can inline them because their bodies are visible. (The #ifndef lines are an include guard, explained in Conditional Compilation.) Our editor compiles a single file, so the next example puts the "header" part at the top of main.c, which is exactly what #include does anyway.

C static inline helpers

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 scanf or fgets), it gets the next line from this box.

It prints three positions, (2.00, 1.50), (3.00, 1.00) and (4.00, 0.50), then dot = 1.875. The small struct-returning helpers read cleanly, and at -O1 the compiler turns them into a few floating-point instructions with no calls.

One cost of static inline in a header: if the compiler decides not to inline, every file that uses the function gets its own copy, which can make the program a bit bigger. For tiny helpers that's irrelevant. For big functions, don't mark them inline at all: declare them in the header and define them once in a .c file.

Plain inline: the C99 rules

Now the surprising part. In C, a function declared inline without static, where every declaration in the file says inline and none says extern, is an inline definition. An inline definition is only an alternative the compiler may use for inlining. It is not an external definition: it doesn't put a callable function into the object file.

If the compiler inlines every call, nobody notices. But if it needs a real function, for a call it decided not to inline or because the program takes the function's address, it emits a call to an external symbol that doesn't exist. The linker then fails. This example fails on purpose:

C A plain inline function that fails to link

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 scanf or fgets), it gets the next line from this box.

The compiler is happy, but the linker reports an error like undefined reference to 'square'. The same thing happens with a simple direct call at -O0, where GCC doesn't inline: code that worked in your optimized build breaks in your debug build. That's why you'll sometimes see "my inline function compiles in release but not in debug" questions.

The fix is to provide exactly one external definition somewhere in the program. You do that by adding a declaration with extern (or a declaration without inline) in one source file that sees the inline definition:

C Providing the external definition

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 scanf or fgets), it gets the next line from this box.

Now it prints 49 and 144. The rule in short:

What a file contains Meaning in C
static inline int f(...) { ... } private copy for this file, emitted only if needed
inline int f(...) { ... } and nothing else inline definition only; no external symbol
the above plus extern inline int f(...); (or int f(...);) inline definition and the one external definition
int f(...) { ... } (no inline) normal external definition

The multi-file layout looks like this:

C
// square.h  (included everywhere)
inline int square(int x) { return x * x; }

// square.c  (compiled once)
#include "square.h"
extern inline int square(int x);

// any other .c file
#include "square.h"
int area_of(int side) { return square(side); }   // may be inlined

This design gives you one shared copy of the function (rather than one per file, as with static inline), at the price of a line to remember. Most projects simply use static inline and never think about it. You'll learn more about headers, extern and linkage in Scope and Storage Classes and Multi-File Programs and Linkage.

A restriction on non-static inline functions

Because an inline definition might be replaced by the external definition in another file, the standard forbids it from relying on things private to its own file. A non-static inline definition must not define a modifiable static local variable and must not refer to file-scope static variables or functions. GCC warns about both:

C
static int calls = 0;

inline int counted(int x)
{
    calls++;          // warning: 'calls' is static but used in inline function
    return x;         //          'counted' which is not static
}

The cure is the same as before: make the function static inline, and the restriction disappears.

How C differs from C++

C++ also has inline, and the keyword looks the same, but the rules are different. In C++, an inline function may be defined in every translation unit that uses it (it must be identical everywhere), and the compiler and linker together make sure one copy survives. You never write the extra extern declaration, and a plain inline function never fails to link.

C (C99 and later) C++
plain inline in a header inline definition only; one file must add extern just works; linker merges copies
static inline private copy per file private copy per file (rarely used)
inline variables don't exist exist since C++17

If you share headers between C and C++, static inline is the form that behaves the same in both languages. The C and C++ lesson of our C++ tutorial lists more differences like this one.

Old GNU code works the other way around. Before C99, GCC had its own inline extension (now called GNU89 inline), where extern inline meant "inline only, never emit a definition", the opposite of C99. Some old code (including older Linux kernel headers) depends on it and is compiled with -fgnu89-inline or __attribute__((gnu_inline)). If you see extern inline function definitions in a header, check which rules the project uses.

Controlling inlining in practice

Since inline is only a hint, compilers offer extensions for the rare cases where you must decide yourself:

  • __attribute__((always_inline)) (GCC/Clang) asks the compiler to inline even at -O0. __forceinline is the MSVC equivalent.
  • __attribute__((noinline)) (GCC/Clang) prevents inlining, which is handy when benchmarking or when you want a function to appear in a profiler.
C
static inline __attribute__((always_inline)) int clamp_byte(int v)
{
    return v < 0 ? 0 : v > 255 ? 255 : v;
}

Use these sparingly. Forcing large functions inline makes code bigger and can make it slower, because it fills the processor's instruction cache. Good practice:

  • Write small helpers as static inline in headers when other files need them, or plain static in a single .c file. The optimizer inlines both.
  • Don't sprinkle inline on big functions hoping for speed. Measure first.
  • Prefer inline functions to function-like macros whenever the job doesn't need the preprocessor.
  • main can never be inline.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does marking a function inline guarantee in C?

    The compiler may ignore the suggestion. The keyword mainly affects how the definition is treated at link time (inline definition vs external definition).
  2. 2. A file contains only inline int twice(int x) { return 2 * x; } and code that takes the address of twice. What happens?

    A plain inline definition is not an external definition. When the program needs a real function, one file must provide it with an extern declaration, or the function should be static inline.
  3. 3. Using #define MAX(a, b) ((a) > (b) ? (a) : (b)), how many times is f() called by MAX(0, f()) if f returns 5?

    The text expands to ((0) > (f()) ? (0) : (f())). f() is called once for the comparison and, because 5 is larger, once more for the result. An inline function would call it once.
  4. 4. Why is static inline the usual choice for small helpers in a header file?

    Internal linkage means no multiple-definition conflicts and no missing external definition. The optimizer can still inline every call because the body is visible.

Summary

  • Inlining replaces a call with the function's body; the compiler decides when, and inlines small functions at -O1 and above even without the keyword.
  • inline is a hint plus a set of linkage rules, not a command.
  • static inline is the everyday form: safe in headers, a private copy per file only when needed, and it behaves the same in C and C++.
  • A plain C99 inline function is only an inline definition. Exactly one file must add extern inline int f(...); to emit the real function, or you get "undefined reference" errors, often only in debug builds.
  • Non-static inline functions can't use file-scope static variables or define modifiable static locals.
  • C++ inline merges copies automatically; old GNU89 code reverses the meaning of extern inline.
  • Prefer inline functions to macros: arguments are evaluated once and types are checked.

Next: Function Pointers, where functions become values you can store, pass and call later.