undefined reference

An undefined reference or unresolved symbol linker error indicates that one of the components of a program refers to a function or object that had been declared to exist but that had never been defined.

= Common problems =

A typical function or object must be defined in exactly one translation unit, although its existence may be declared in a header file and referenced throughout the program. As a special case, templates, inline functions, and  objects may be defined in a header file, and the compiler and linker will take care of the rest.

Mismatched signatures
When supplying definitions, double-check the name, scope, function arguments, and CV-qualifiers:

NOTE: If you actually have a member function like  that isn't virtual and doesn't use any private or protected members of its class, then consider that it probably shouldn't be a member function at all!

and objects
Uninitialized declarations must have separate definitions:

/* foo.h */ extern const int  g_answer; extern const float g_pi;

struct Class { static const int s_answer; static const int s_pi; };

/* foo.cpp */ const int  g_answer        = 42; const float g_pi           = 3.14f; const int  Class::s_answer = 42; const float Class::s_pi    = 3.14f;

Initialized declarations of  objects define themselves, and they must not have separate definitions:

/* foo.h */ extern const int  g_answer = 42; extern const float g_pi    = 3.14f;

/* foo.cpp */ const int  g_answer; // ERROR: already defined const float g_pi;    // ERROR: already defined

Initialized declarations of  integer objects must have separate definitions if you refer to them by address, and may have definitions in other cases:

/* foo.h */ struct Class { static const int s_answer = 42; static const int s_other = 42; };

/* foo.cpp */ int n = Class::s_answer;       // no definition needed; just sets n = 42 const int Class::s_answer;     // optional

const int *p = &Class::s_other; // needs the address of the definition const int Class::s_other;      // required

Note that declarations must not be initialized for non-   objects and non-  or non-integer   member objects:

extern int g_answer = 42;  // ERROR: not const

struct Class { static int s_answer = 42; // ERROR: not const static const float s_pi; // ERROR: not an integer };

Linkage
Obviously, make sure that you actually link your definitions into your program.

Templates and inline functions
In general, templates and inline functions must be defined in each translation unit that uses them. This usually involves defining the template in the header file, like so:

/* tmpl.hpp */
 * 1) include

template void f (T x) { std::cout << "x = " << x << '\n'; }

/* main.cpp */
 * 1) include "tmpl.hpp"

int main { f(42); }

Note that there are some cases where this is not true, notably explicit template instantiation.