What are undefined reference/unresolved external symbol errors? What are common causes, and how do I fix and prevent these errors?
C++: How to Fix Undefined Reference/Unresolved External Symbol Errors
c++c++-faqlinker-errorsundefined-referenceunresolved-external
Best Answer
Say you have the following code:
When compiling
b.cpp
, the compiler simply assumes thatget()
symbol was defined somewhere, but it doesn't yet care where. The linking phase is responsible for finding the symbol and correctly linking the object files produced froma.cpp
andb.cpp
.If
a.cpp
didn't defineget
, you would get a linker error saying "undefined reference" or "unresolved external symbol".C++ Standard Wording
Compiling a C++ program takes place in several phases specified in [lex.phases], the last of which is relevant:
See Keith Thompson's answer for a summary of these phases.
The specified errors occur during this last stage of compilation, most commonly referred to as linking. It basically means that you compiled a bunch of source files into object files or libraries, and now you want to get them to work together.
Linker Errors in Practice
If you're using Microsoft Visual Studio, you'll see that projects generate
.lib
files. These contain a table of exported symbols, and a table of imported symbols. The imported symbols are resolved against the libraries you link against, and the exported symbols are provided for the libraries that use that.lib
(if any).Similar mechanisms exist for other compilers/ platforms.
Common error messages are
error LNK2001
,error LNK1120
,error LNK2019
for Microsoft Visual Studio andundefined reference to
symbolName for GCC.The code:
will generate the following errors with GCC:
and similar errors with Microsoft Visual Studio:
Common Causes
#pragma
(Microsoft Visual Studio)UNICODE
definitions