0
0
CppDebug / FixBeginner · 3 min read

How to Fix Linker Error in C++: Simple Steps

A linker error in C++ happens when the compiler finds a function or variable declaration but cannot find its definition during linking. To fix it, ensure all functions and variables are defined and all source files are compiled and linked together correctly.
🔍

Why This Happens

A linker error occurs when you declare a function or variable but forget to provide its actual code or definition. The compiler sees the declaration and assumes the definition exists somewhere else, but the linker cannot find it when combining all parts of your program.

cpp
#include <iostream>

void greet(); // Declaration only

int main() {
    greet();
    return 0;
}
Output
undefined reference to `greet()` collect2: error: ld returned 1 exit status
🔧

The Fix

To fix the linker error, provide the missing function definition. This means writing the actual code for the declared function. Also, make sure all source files are compiled and linked together.

cpp
#include <iostream>

void greet() {
    std::cout << "Hello, world!" << std::endl;
}

int main() {
    greet();
    return 0;
}
Output
Hello, world!
🛡️

Prevention

Always define every declared function and variable. Use your IDE or build system to compile and link all source files together. Avoid declaring functions without definitions. Use header files for declarations and source files for definitions. Tools like lint or compiler warnings can help catch missing definitions early.

⚠️

Related Errors

Other common errors include:

  • Multiple definition errors: Defining the same function or variable in more than one source file.
  • Undefined reference to template functions: Templates need definitions visible in all files using them.
  • Missing libraries: Forgetting to link external libraries your code depends on.

Key Takeaways

Linker errors mean declared functions or variables lack definitions.
Always provide definitions for all declared functions and variables.
Compile and link all source files together to avoid missing code.
Use header files for declarations and source files for definitions.
Check for missing libraries or multiple definitions when linking.