如何正确定义C ++类析构函数并将其链接到主文件? [英] How to correctly define and link a C++ class destructor to a main file?

查看:62
本文介绍了如何正确定义C ++类析构函数并将其链接到主文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是来自 mingw32/bin/ld.exe ...对[class] ... collect2.exe的未定义引用:错误:ld返回1退出状态

MyClass.hpp中有一个用户定义的类:

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;
}

错误:

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

有两个问题:1.如何构建Makefile或可以使用哪个g ++命令将MyClass正确链接到Main?2. g ++如何使用这个自己的默认析构函数(在这种情况下,我根本没有定义它,但仍然无法正常工作).或者,如果我需要自己定义一个,最好的方法是怎么做?

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?

简单的编译命令:

g++ -o MyProgram.exe Main.cpp -Wall

我还尝试了来自以下文件的Makefile:

I also tried the Makefile from : mingw32/bin/ld.exe ... undefined reference to [class] ... collect2.exe: error: ld returned 1 exit status

然后我通过以下方法检查了工具链的依赖性:Makefile:如何正确包含头文件及其目录?

And I checked the toolchain dependencies by following : Makefile: How to correctly include header file and its directory?

推荐答案

我遇到了与您相同的问题.尝试将构造函数和析构函数定义从cpp移到头文件中.这样,只有通过运行您提到的简单g ++命令,才能很好地完成链接.

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.

尝试:

MyClass(const string& className){ _className=className }; 

如果该定义位于cpp文件中,则会收到与您相同的错误.

If the definition is inside the cpp file, I get the same error as you have.

这篇关于如何正确定义C ++类析构函数并将其链接到主文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆