问题
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?
回答1:
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.
回答2:
Do you have MyClass
constructor and destructor definition (like specified) in your header file? Do you use Makefile or only try to execute g++ via terminal?
Linker needs compiled object of MyClass
. If you compile main.cpp to entire executable it should contain all declared definitions.
来源:https://stackoverflow.com/questions/59895532/how-to-correctly-define-and-link-a-c-class-destructor-to-a-main-file