skip to content

Why does a C++ function template defined only in a .cpp file cause an undefined-symbol link error when another file calls it?

level: juniorimportance: must knowfreq 75%

answer

  1. a template is a recipe, not code
  2. instantiation needs the body in view
  3. caller emits only an external reference
  4. explicit instantiation in the .cpp file

basics

~20 s

A template generates code only when it is instantiated, and the compiler can instantiate it only where the definition is visible. The calling file sees just the declaration, so it references to_bytes<int>, which no object file ever defines.

solid answer

~50 s

A function template is not a function; it is a recipe the compiler turns into one when a translation unit needs, say, `to_bytes<int>`. That *implicit instantiation* needs the template's definition in the same translation unit. `main.cpp` includes only the declaration, so the compiler assumes the specialization is defined elsewhere and emits an external reference. `ser.cpp` holds the body but never uses it with `int`, so it instantiates nothing. The linker then finds no `to_bytes<int>` anywhere. The usual fix is to define the template in the header, so every caller can instantiate it; the one-definition rule allows a templated entity to be defined in several translation units as long as the definitions are identical. The alternative is an explicit instantiation definition in `ser.cpp`, `template std::string to_bytes<int>(const int&);`, which works only for the argument types you list.

code

cpp · 9 lines
cpp
// ser.cpp: the body stays here; ser.h holds only the declaration
#include "ser.h"

template <class T> std::string to_bytes(const T& value) {
    return std::string(reinterpret_cast<const char*>(&value), sizeof value);
}

// Explicit instantiation definition: emit to_bytes<int> in this object file
template std::string to_bytes<int>(const int&);

go deeper

for a junior

Recall that a template is a pattern, that each argument set produces its own function, and that the body must be visible where it is used, which is why template code lives in headers.

for a middle

Walk through the three tools: the caller emits an undefined reference, the defining file instantiates nothing because nothing uses it there, and the linker finds the gap. Name explicit instantiation as the alternative fix.

for a senior

Explain why many identical instantiations link cleanly, why a full specialization in a header needs inline, and when a closed type set justifies explicit instantiation in a .cpp file.

for a principal

Connect the header model to build cost: every user re-instantiates the same specializations, and the choice between header-only and explicitly instantiated templates is a build-time and API decision.

## What a template is to the compiler A **function template** such as `template <class T> std::string to_bytes(const T& value)` is not a function. It is a pattern from which the compiler generates functions, one per distinct set of template arguments. Each generated function is a **specialization**: `to_bytes<int>`, `to_bytes<double>` and `to_bytes<Record>` are three separate functions with three separate symbols in the object files. Generating one is called **instantiation**. When a translation unit (one `.cpp` file after preprocessing) calls `to_bytes(42)`, the compiler deduces `T = int` and must produce `to_bytes<int>`. To produce it, it needs the template's **definition** — the body — at that point. A declaration is enough to type-check the call, but not to generate code. ## The failing build, step by step Take a library split the way ordinary functions are split: - `ser.h` declares `template <class T> std::string to_bytes(const T& value);` - `ser.cpp` includes `ser.h` and defines the body - `main.cpp` includes `ser.h` and calls `to_bytes(42)` What each tool does: 1. Compiling `main.cpp`: deduction picks `T = int`. There is no body in view, so the compiler cannot instantiate it. It treats `to_bytes<int>` as a function defined somewhere else and emits an **undefined reference** to its mangled name. 2. Compiling `ser.cpp`: the body is there, but nothing in `ser.cpp` uses `to_bytes<int>`. A template is instantiated only when a specialization is needed, so `ser.o` contains **no** `to_bytes` code at all. 3. Linking: `main.o` asks for `to_bytes<int>(int const&)`, no object file defines it, and the link fails; Apple's `ld` reports `Undefined symbols for architecture arm64`. The compiler never complains. Each translation unit is valid on its own; the gap shows only when the pieces meet. ## Three ways to fix it | Fix | How | Who can use new types | |---|---|---| | Definition in the header | Move the body into `ser.h` (or an included `ser.tpp`) | Every caller, for any `T` | | Explicit instantiation | `template std::string to_bytes<int>(const int&);` in `ser.cpp`, after the body | Only the types you list | | Non-template overloads | Write `to_bytes(const int&)` etc. as ordinary functions | Only the overloads you write | Defining the template in the header is the default, and it is how the standard library ships its templates. An **explicit instantiation definition** — `template` followed by a declaration, with no `<>` — tells the compiler to generate that specialization in this translation unit even though nothing there calls it. It suits a library with a closed, known set of argument types, and it keeps the body out of every caller's compile. ## Why duplicate copies do not clash If fifty `.cpp` files include the header and call `to_bytes(42)`, all fifty object files carry a copy of `to_bytes<int>`. That is not a multiple-definition error. The one-definition rule lists a **templated entity** among the items that may be defined in more than one translation unit, provided every definition is identical; only a non-inline, non-templated function or variable is limited to one. In practice, toolchains emit each implicit instantiation as a mergeable weak symbol and the linker keeps one copy — an implementation's mechanism, not something the standard spells out. A full specialization, `template<> std::string to_bytes<bool>(const bool&)`, is different: it is an ordinary function, so a definition in a header needs `inline`. ## Common wrong turns - **`export` templates.** C++03 had `export template` to allow separate compilation; it never reached implementation consensus, it was removed, and since C++20 `export` belongs to modules. - **Marking the declaration `inline`.** That changes linkage rules, not visibility of the body; the caller still cannot instantiate it. - **Expecting the linker to instantiate.** Mainstream toolchains instantiate in the compiler; the linker only resolves symbols. ## What it costs Header-defined templates are re-parsed and re-instantiated in every translation unit that uses them, which is a large share of build time in template-heavy code. Explicit instantiation with `extern template` exists to trade some of that back. The header model also explains everyday error messages. A typo inside a template body that depends on `T` is reported only when some file instantiates the template, and the error appears at the point of use with a chain of `in instantiation of` notes leading back to it. Reading that chain from the bottom up — the caller's line first — is usually the quickest way to find which argument type exposed the bug.

  • If ser.cpp explicitly instantiates the class template Serializer<Record>, which members does it generate?
    `template class Serializer<Record>;` is an explicit instantiation definition of the class and of every member that is already defined at that point in the file. Members defined later, or in another file, are not instantiated by it. So the out-of-line member definitions must be visible above the line, which is why it usually sits at the bottom of the `.cpp` that holds them.
  • Why does a full specialization defined in a header need inline when the primary template does not?
    A full specialization such as `template<> std::string to_bytes<bool>(const bool&)` is not a templated entity; it is an ordinary function. The one-definition rule lets a templated entity be defined identically in many translation units, but a non-inline, non-templated function only once. Without `inline`, every file including the header defines it again; the program is ill-formed, and linkers typically report a duplicate symbol.

  • The compiler rejects the call because the template body is not visible in main.cpp.
  • The linker instantiates to_bytes<int> from ser.cpp's definition when it sees the reference.
  • Templates in headers break the one-definition rule, so each copy must be declared static.
  • Marking the declaration inline in the header fixes the undefined symbol.
  • In modern C++ the export keyword lets a template body stay in its .cpp file.