What does undefined reference to mean in C++?
Understanding the Linker Error
In C++, the compiler translates each source file into an object file. The linker then combines these object files and libraries to create an executable. If a symbol (like a function) is declared and used but never defined, the linker reports an 'undefined reference'.
This error is different from a compiler error; it happens at the linking stage. The message often includes the name of the missing symbol and the object file where it was referenced.
- Common with functions declared in headers but not implemented.
- Occurs when a library is not linked (e.g., missing -lm for math functions).
- Can happen with static class members that are not defined outside the class.
How to Resolve It
First, ensure that every declared function or variable has a definition. If it's in a separate source file, make sure that file is compiled and linked. If it's from a library, add the correct linker flag (e.g., -l for Unix-like systems).
For static class members, you must provide a definition outside the class. Also, check for name mangling issues when mixing C and C++ code; use extern "C" where appropriate.
If you're using an IDE, verify that all source files are included in the build and that library paths are set correctly.
- Compile all source files together or link their object files.
- Add necessary libraries to the linker command.
- Define static members outside the class definition.
Common mistakes
- Confusing 'undefined reference' with 'unresolved external symbol' (the latter is the Microsoft equivalent).
- Thinking that declaring a function in a header is enough; you still need a definition.
- Forgetting to link the math library when using functions like sqrt or sin.
