Open In App

How to Fix Undefined Reference Error in C++?

In C++, the undefined reference error typically occurs during the linking phase of compilation. This error indicates that the compiler knows about a function or variable (it has been declared), but it cannot find the actual implementation (definition) during the linking process. The linker needs to resolve these references to create a complete executable.

In this article, we will discuss how to fix undefined reference errors in C++.



Fix Undefined Reference Errors in C++

Below are some practical situations of undefined reference errors and the solution to fix them:

1. Define the Function and Variables

Undefined reference errors are mostly caused due to missing function definitions. So, if we have declared a function or variable but forgot to provide its implementation, we need to define it.



Example




// C++ program to fix undefined reference error
#include <iostream>
using namespace std;
  
// Declaration without definition
void myFunction();
  
int main()
{
    // Call to undefined function
    myFunction();
    return 0;
}

Output

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

2. Linking Necessary Libraries

Make sure that you are linking all necessary source files, object files and libraries during compilation and if you split your code into multiple files make sure that all object files are linked correctly.

For Example, linking mylib source file, use the following command:

g++ main.cpp myFunctions.cpp -o myProgram -lmylib

3. Check for Namespace and Scope Issues

If you are using namespaces, make sure the function/variable is in the correct namespace and included in the main file also variables are defined within the scope.

Example




// C++ to show undefined reference error due to incorrect
// namespace
#include <iostream>
  
namespace MyNamespace {
void myFunction();
}
  
// Definition inside the namespace
void MyNamespace::myFunction()
{
    std::cout << "Hello from MyNamespace::myFunction!\n";
}
  
int main()
{
    myFunction();
    return 0;
}

Output

main.cpp: In function ‘int main()’:
main.cpp:17:5: error: ‘myFunction’ was not declared in this scope; did you mean ‘MyNamespace::myFunction’?
17 | myFunction();
| ^~~~~~~~~~
| MyNamespace::myFunction
main.cpp:10:6: note: ‘MyNamespace::myFunction’ declared here
10 | void MyNamespace::myFunction()

Conclusion

We encounter the ‘undefined reference’ error in C++ mostly due to issues with function or variable definitions, improper linking, or scope/naming problems. By careful checking the code and build process for these common issues, we can successfully resolve this error.


Article Tags :