C++

Fix Template "Undefined Reference" — Why Template Definitions Cannot Hide in a .cpp

Split a template the way you split an ordinary class — declaration in the header, definitions in a .cpp — and both files compile, then the link fails with an undefined reference for every member the program actually calls. This guide builds that failure on purpose, reads the linker output line by line, and shows why neither file is at fault on its own: the file that uses the template cannot see the definitions it would need to generate the code, and the file that holds the definitions never generates any code because nothing in it asks for a concrete type. Two fixes follow — move the definitions into the header, or keep them in the .cpp and name the exact types with explicit instantiation — plus the limit of the second fix and the one member that never needed fixing.

Written November 18, 2026 · Tested with GCC 13.3 · 12 min read

By the end of this guide
  • The broken split: compiles twice, links never
  • Why neither file generates the code
  • Fix one: put the definitions where the use can see them
  • Fix two: keep the .cpp, and name the types — explicit instantiation

What this guide is

An ordinary class can live in two places: the header declares it, a source file defines its members, and any file that includes the header can use it, because the linker joins the call sites to the one set of definitions. A template looks like it should split the same way, and it does not. The examples here use C++17 and GCC 13.3. The Box examples thread the same three files — a header named box.h, a source file named box.cpp, and a main.cpp — through the guide; only where the definitions sit changes. Two smaller examples near the end use the same shape with files of their own.

The header declares a class template and nothing more. It names the class, its data member, and three member functions, and it defines none of them:

C++
// box.h
#pragma once
template <typename T>
struct Box {
    T value;
    explicit Box(T v);
    T get() const;
    void set(T v);
};

The source file holds the definitions, written exactly as member definitions of an ordinary class would be, with the template parameter in scope:

C++
// box.cpp
#include "box.h"
template <typename T>
Box<T>::Box(T v) : value(v) {}
template <typename T>
T Box<T>::get() const { return value; }
template <typename T>
void Box<T>::set(T v) { value = v; }

The program that uses the class includes only the header, as a caller should:

C++
// main.cpp
#include "box.h"
#include <iostream>
int main() {
    Box<int> b(41);
    b.set(42);
    std::cout << "value=" << b.get() << "\n";
    return 0;
}

Compile each file on its own and both compile without a complaint. The failure arrives when the two object files are linked:

Terminal
$ g++ -std=c++17 -Wall -Wextra -c box.cpp -o box.o
$ g++ -std=c++17 -Wall -Wextra -c main.cpp -o main.o
$ g++ box.o main.o -o prog
/usr/bin/ld: main.o: in function `main':
main.cpp:(.text+0x29): undefined reference to `Box<int>::Box(int)'
/usr/bin/ld: main.cpp:(.text+0x3a): undefined reference to `Box<int>::set(int)'
/usr/bin/ld: main.cpp:(.text+0x62): undefined reference to `Box<int>::get() const'
collect2: error: ld returned 1 exit status

Read the output as a list of missing functions, not as noise. There are three errors, one for each member main calls: the constructor, set, and get. Every name carries the same type argument, int, because the missing functions are not the template's members in the abstract — they are the int versions of those members, the concrete functions the program needs. Nothing points into box.cpp, even though that is where the definitions are written. The linker works with object files, not source files, and neither object file contains the code for Box<int> at all. The next section explains why each file, for its own reason, produced none.

Why neither file generates the code

A class template by itself is not a class, and a function template by itself is not a function. No code is generated from a source file that contains only template definitions. Code appears only when a template is instantiated: the template arguments are provided, and the compiler generates the actual class or function for those arguments.

That rule splits the broken program into two halves that each fail to do the one job. In box.cpp, the definitions are present, but nothing in that file ever names a concrete type. No Box<int> is constructed, no member is called, so no instantiation is requested and the compiler generates no code from the definitions it read. The object file holds no Box functions for the linker to find. In main.cpp, the use is concrete — a Box<int> is constructed and two members are called — so that file does request an instantiation of each member it uses. But instantiation means generating the member from its definition, and the definition is not in that file: main.cpp saw only the declarations in the header. Unable to generate the code, the compiler writes the calls as references to functions that must exist somewhere else, and the linker then reports, correctly, that they exist nowhere.

This is the difference from an ordinary class. For a non-template member, the definition in the .cpp is compiled once, on its own, into a real function with a name the linker can match. For a template member, the .cpp holds a recipe, not a function. A recipe generates a function only in a file that both reads the recipe and names the type to cook for — and in the broken split, no file does both.

Fix one: put the definitions where the use can see them

The standard fix moves the definitions into the header, so every file that uses the template also reads the definitions it needs:

C++
// box.h
#pragma once
template <typename T>
struct Box {
    T value;
    explicit Box(T v) : value(v) {}
    T get() const { return value; }
    void set(T v) { value = v; }
};

box.cpp is gone from the build. The same main.cpp, unchanged, now builds and runs:

Terminal
$ g++ -std=c++17 -Wall -Wextra main.cpp -o prog
$ ./prog
value=42

Any type works in this shape, including types the author of Box never thought of, because the generation happens at each point of use from the definitions the using file has read. The cost is the one header code always carries: the definitions are part of every file that includes the header, so a change to a definition recompiles every includer, and the implementation is visible to every reader of the header. For most templates that cost is simply the price of the type being open to any argument, and it is why template libraries are usually header-only — not as a style preference, but because the definitions have to be present where the instantiations are requested.

A variation keeps the definitions in a separate file without giving up the visibility: the header includes the definition file at its end, often named box.tpp or box_impl.h, after the declarations. Every includer still reads the definitions, so the mechanism is identical; only the filing differs.

Fix two: keep the .cpp, and name the types — explicit instantiation

The .cpp split can be kept when the set of types is closed and known in advance. The missing step is to tell the defining file which types to generate. An explicit instantiation definition in box.cpp, after the member definitions, does exactly that:

C++
// box.cpp
#include "box.h"
#include <string>
template <typename T>
Box<T>::Box(T v) : value(v) {}
template <typename T>
T Box<T>::get() const { return value; }
template <typename T>
void Box<T>::set(T v) { value = v; }
template struct Box<int>;
template struct Box<std::string>;

Each template struct line forces the instantiation of that specialization in this file, members included, whether or not anything in the file uses it. Naming a class template specialization in an explicit instantiation definition also instantiates each of its non-template members that has been defined at that point, which is why the lines must come after the definitions, and why the definition of the class template must be present in this file — it is, because box.cpp includes the header and adds the definitions itself. The program can now use both named types:

C++
// main.cpp
#include "box.h"
#include <iostream>
#include <string>
int main() {
    Box<int> b(41);
    b.set(42);
    std::cout << "value=" << b.get() << "\n";
    Box<std::string> s(std::string("hi"));
    std::cout << "text=" << s.get() << "\n";
    return 0;
}
Terminal
$ g++ -std=c++17 -Wall -Wextra box.cpp main.cpp -o prog
$ ./prog
value=42
text=hi

The same mechanism covers function templates, with the function's own syntax. A function template declared in a header and defined in a .cpp gets one explicit instantiation line per signature the program needs:

C++
// twice.h
#pragma once
template <typename T>
T twice(T v);
C++
// twice.cpp
#include "twice.h"
template <typename T>
T twice(T v) { return v + v; }
template int twice<int>(int);
template double twice<double>(double);
C++
// main.cpp
#include "twice.h"
#include <iostream>
int main() {
    std::cout << "int=" << twice<int>(21) << "\n";
    std::cout << "double=" << twice<double>(1.5) << "\n";
    return 0;
}
Terminal
$ g++ -std=c++17 -Wall -Wextra twice.cpp main.cpp -o prog
$ ./prog
int=42
double=3

One addition makes the closed set explicit to the using files as well. An explicit instantiation declaration — the same line with extern in front of it, placed in the header or in the using file — tells the compiler not to instantiate that specialization locally, because the explicit definition elsewhere will provide it:

C++
// in a file that uses twice<int>
extern template int twice<int>(int);

Since C++11 this declaration suppresses the implicit instantiation the use would otherwise trigger in that file. It is an optimization and a statement of intent, not a requirement. The link in the twice program succeeds without it for a simpler reason: main.cpp sees only the declaration, so it generates nothing and simply refers to the functions that the explicit definitions in twice.cpp provide. Where a definition is visible in several translation units at once — the header shape of fix one — each unit may generate the same specialization and the linker keeps one copy; that merging is a separate mechanism. What is required is only that the one explicit definition exists somewhere in the program, exactly once for each set of template arguments.

The trap in fix two: the closed set is closed

Trap
Explicit instantiation trades the open template for a list, and the list is the whole contract. The first caller that reaches for a type outside it brings the original error back, for that type only. Keep the box.cpp from fix two and change main to use a double:
C++
// main.cpp
#include "box.h"
#include <iostream>
#include <string>
int main() {
    Box<double> d(1.5);
    std::cout << "value=" << d.get() << "\n";
    return 0;
}
Terminal
$ g++ -std=c++17 -Wall -Wextra -c box.cpp -o box.o
$ g++ -std=c++17 -Wall -Wextra -c main.cpp -o main.o
$ g++ box.o main.o -o prog
/usr/bin/ld: main.o: in function `main':
main.cpp:(.text+0x30): undefined reference to `Box<double>::Box(double)'
/usr/bin/ld: main.cpp:(.text+0x58): undefined reference to `Box<double>::get() const'
collect2: error: ld returned 1 exit status

Two details in that output are worth reading. The missing names carry double, not int or std::string — the named types still link, because their code was generated. And there are two errors, not three: this main never calls set, so no Box<double>::set was requested, and a member nobody requests is a member nobody misses. The fix for the new type is one more line in box.cpp, template struct Box<double>; — and a decision about whether the set was really closed. A template that keeps gaining instantiation lines for types its users choose freely is a header template wearing a .cpp costume, and moving the definitions into the header is the honest shape for it. Keep fix two for sets that are closed by the problem itself: the numeric types a solver supports, the message types a protocol defines, the node types of one data structure family.

The member that never needed a definition

One consequence of instantiation-on-use surprises people in the other direction: a member function of a class template that is declared, never defined, and never called costs nothing. The members of a class template are instantiated only when they are used, so an unused member does not require a definition to exist:

C++
// widget.h
#pragma once
template <typename T>
struct Widget {
    T value;
    explicit Widget(T v) : value(v) {}
    T get() const { return value; }
    T missing() const;
};
C++
// main.cpp
#include "widget.h"
#include <iostream>
int main() {
    Widget<int> w(7);
    std::cout << "value=" << w.get() << "\n";
    return 0;
}
Terminal
$ g++ -std=c++17 -Wall -Wextra main.cpp -o prog
$ ./prog
value=7

missing has no definition anywhere, and the program links and runs, because no code ever asks for Widget<int>::missing. Add one call to it and the same program fails to link with an undefined reference to exactly that member. This is also why the broken split in the first section reported only the members main called: the linker error is always a list of what was used and not found, never a list of everything that was defined in the wrong place.

Which fix for which template

Shape of the problem Fix Why
Any caller may use any type, including types written after the template Definitions in the header Instantiation happens at each point of use, from definitions the using file has read
Definitions are long, and recompiling every includer on each change is a real cost, but the type set is small and fixed Definitions in the .cpp plus one explicit instantiation line per type The defining file generates exactly the named specializations, once
A function template with a fixed set of signatures Definitions in the .cpp plus one explicit instantiation line per signature Same closed-set mechanism, at function scope
A type set that keeps growing as callers choose new types Move the definitions into the header The closed set was not closed; each new type otherwise returns as the same link error
A member declared but never called by any program Nothing Members of a class template are instantiated only when used, so no definition is required

Checklist

  • Before splitting a template into a header and a .cpp, ask whether the set of types is closed. If it is not, the definitions belong in the header from the start.
  • Before hunting for a typo in an undefined-reference error, read the type argument in the missing name. An error naming Box<double> in a program whose .cpp instantiates Box<int> is a missing instantiation line, not a broken definition.
  • Before adding an explicit instantiation line, confirm it sits after the definitions in the .cpp. An explicit instantiation of a class template instantiates the members that have been defined at that point, and no others.
  • Before concluding a member is missing, check whether anything calls it. The linker lists only the members that were used, so a member absent from the error list may be undefined and unused, and both halves of that matter.
  • Before blaming the header for a template link error, check which file was supposed to generate the specialization. If no file both read the definition and named the type — by use or by an explicit instantiation line — no file generated it.

Sources

  • cppreference, Class template — a class template is not a type or an entity by itself, no code is generated from a file containing only template definitions, instantiation is what generates the class, and the explicit and implicit instantiation rules, including that a class template's members are instantiated only when used.
  • cppreference, Function template — the same generation rule for function templates, the explicit instantiation definition and declaration syntax, and that an explicit instantiation definition forces instantiation and may appear only once in the program for a given set of arguments.

Keep Exploring