How do I fix an unresolved external symbol error in C++?
What it means
The compiler compiles each source file separately. When you declare a function but don't define it, the compiler is fine, but the linker looks for the definition and fails if it can't find it.
This often happens when you forget to link a library, misspell a function name, or forget to include a source file in your build.
- You declared a function but never defined it.
- You forgot to link against a required library.
- The function signature in the definition doesn't match the declaration.
- You're using a function from a library but didn't include its .lib or .a file.
- The definition is in a source file not included in the build.
How to fix it
First, check that the function or variable is actually defined somewhere. If it's in a library, make sure you're linking that library in your build settings.
If it's your own code, ensure the source file containing the definition is part of the project. Also check for name mangling issues, especially when mixing C and C++.
On Windows, you might need to use __declspec(dllexport) and __declspec(dllimport) for DLLs. On Linux, ensure the library is in the linker path.
Common mistakes
- Assuming the compiler error is the only problem; unresolved external is a linker error, not a compiler error.
- Forgetting to add the library to the linker command line, even if the header is included.
- Mismatching function signatures between declaration and definition, e.g., missing const or different parameter types.
