Issue
This is a particularized question from mingw32/bin/ld.exe ... undefined reference to [class] ... collect2.exe: error: ld returned 1 exit status
There is a user-defined class inside MyClass.hpp:
class MyClass
{
public:
MyClass(const string& className);
~MyClass() {cout << "Destructor definition instead of g++ default one?";} ;
...
and you try to construct an object out of it in the main file:
#include "MyClass.hpp" //in the same directory
...
int main()
{
...
MyClass myClassObj = MyClass(myName); //here is the linker problem
...
return 0;
}
The error:
c:/mingw/bin/../lib/gcc/mingw32/8.2.0/../../../../mingw32/bin/ld.exe: C:\Users\....:Main.cpp:(.text+0x124c): undefined reference to `MyClass::~MyClass()'
collect2.exe: error: ld returned 1 exit status
There are two questions: 1. How can I build a Makefile or which g++ command can I use to have the correct linkage of MyClass into Main? 2. How can g++ use this own default destructor (in this case I did not defined it at all, still not working). Or, if I need to define one myself, how is the best way to do it?
simple compilation command:
g++ -o MyProgram.exe Main.cpp -Wall
I also tried the Makefile from : mingw32/bin/ld.exe ... undefined reference to [class] ... collect2.exe: error: ld returned 1 exit status
And I checked the toolchain dependencies by following : Makefile: How to correctly include header file and its directory?
Solution
I had the same problem as you. Try to move your constructor and destructor definition from the cpp into the header file. This way, the linkage is well done only by running the simple g++ command that you mentioned.
Try:
MyClass(const string& className){ _className=className };
If the definition is inside the cpp file, I get the same error as you have.
Answered By - kaileena