As a beginner c++ developer , you probably might get error like undefined reference to `main’.
Generally this error occurs when we forgot not define main() function in program. In any c++ program main() function is necessary to start a program. So whenever you create any class then do not forgot to add main function in your project and then you can call class functions from main.
undefined reference to ‘main’ c++
#include <iostream>
using namespace std;
class A{
public:
int GetValue();
};
int A::GetValue()
{
return 0;
}
Output:
Here we have just created class inside our program and not define any main function. So here we are getting error undefined reference to main c++.
SOLUTION : Undefined reference to main c++
We can resolve this error by adding main function inside program.
#include <iostream>
using namespace std;
class A{
public:
int GetValue();
};
int A::GetValue()
{
return 0;
}
int main()
{
return 0;
}
Also many time possible for new developer of someone coming from C# background that they define main() function inside class. So just remember that we have to define main() function as a global in C++.
// Declare global inside file
int main()
{
return 0;
}
undefined reference to func() c++
When we declare and function but not added it’s definition then we get undefined reference to func c++ error.
#include <iostream>
using namespace std;
void func();
int main()
{
func();
return 0;
}
Here we will get error by compiler :
Compilation failed due to following error(s). main.cpp:(.text+0x5): undefined reference to `func()’
SOLUTION : Undefined reference to function c++
We can resolve it by adding c++ function definition.
#include <iostream>
using namespace std;
void func();
int main()
{
func();
return 0;
}
void func()
{
cout<<"Hello";
}
CONCLUSION:
Make sure in c++ whenever you are getting any compilation errors like undefined reference to main c++ or undefined reference to func c++ ( here func can be any name of function.) then you have to add definition of that function inside your file. Once you have added definition of function then you will not get any undefined reference c++ error and program will be executed successfully.
Leave a Reply