Open In App

What is an Undefined Reference Error in C++?

In C++, an undefined reference is an error that occurs when the linker can’t find the definition of a function or a variable used in the linking stage of the compilation process. This error needs to be resolved for the smooth working of the program.

When Does Undefined Reference Error Occur in C++?

An undefined reference error is a linker error, not a compiler error. It appears when the code refers to a symbol (function or variable) whose declaration is known, but whose definition is missing. We get undefined reference errors due to the following reasons:



  1. Function or Variable Declaration Without Definition.
  2. Incorrect Scope Resolution.
  3. Incorrect Linking of Object Files or Libraries.

Example of Undefined Reference Error

The below example demonstrates the occurrence of an undefined reference error due to a missing function definition.




// C++ example demonstrating an undefined reference error.
#include <iostream>
  
// Declare `newFunction` but don't provide its
// implementation.
void newFunction();
  
int main()
{
    // Calling this triggers an error because `newFunction`
    // is undefined.
    newFunction();
  
    return 0;
}

Output



/usr/bin/ld: /tmp/cceTEmEf.o: in function `main':
main.cpp:(.text+0x9): undefined reference to `newFunction()'
collect2: error: ld returned 1 exit status

To resolve this, make sure to provide a proper definition for the function:




// C++ program demonstrating a corrected undefined reference
// error
#include <iostream>
using namespace std;
  
// Function that prints "This is new function"
void newFunction() { cout << "This is new function"; }
  
int main()
{
    newFunction();
  
    return 0;
}

Output
This is new function

How to Avoid Undefined Reference Error in C++

To avoid undefined errors in our C++ program, we can follow the given steps:

To know more about how to fix these kinds of errors, refer to this article – How to fix undefined error in C++?


Article Tags :