0
0
CDebug / FixBeginner · 3 min read

How to Fix Undefined Reference Error in C: Simple Steps

An undefined reference error in C happens when the linker cannot find the definition of a function or variable you declared. To fix it, ensure you provide the function's implementation and link all necessary source files or libraries during compilation.
🔍

Why This Happens

This error occurs because the compiler found a declaration or usage of a function or variable, but the linker could not find its actual code or data. This usually happens when you declare a function in a header or source file but forget to provide its definition or forget to link the file containing it.

c
#include <stdio.h>

void greet(); // Declaration only

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

The Fix

To fix this, you must provide the function's definition. You can add the function code in the same file or in another file and link it properly. Here, we add the greet function definition below main.

c
#include <stdio.h>

void greet() {
    printf("Hello, world!\n");
}

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

Prevention

Always provide definitions for all declared functions and variables. When using multiple files, compile and link all source files together. Use build tools or IDEs that manage linking automatically. Running a linter or compiler warnings can help catch missing definitions early.

⚠️

Related Errors

Other common linker errors include:

  • Multiple definition: When the same function or variable is defined in more than one file.
  • Missing library: When you forget to link an external library that provides needed functions.
  • Typo in function name: Declaring and defining functions with different names causes undefined references.

Key Takeaways

Undefined reference means the linker can't find a function or variable definition.
Always provide function definitions for declared functions.
Link all source files that contain needed code during compilation.
Use compiler warnings and linters to catch missing definitions early.
Check for typos and correct library linking to avoid related errors.