How to correctly define and link a C++ class destructor to a main file?

牧云@^-^@ 提交于 2021-02-11 07:20:24

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!