如何正确定义C++类析构函数并将其链接到主文件?



这是来自mingw32/bin/ld的一个具体问题.exe ...对 [类] 的未定义引用...collect2.exe:错误:ld 返回 1 个退出状态

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

class MyClass
{
public:
MyClass(const string& className); 
~MyClass() {cout << "Destructor definition instead of g++ default one?";} ; 
...

然后你尝试在主文件中构造一个对象:

#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++ 如何使用这个自己的默认析构函数(在这种情况下,我根本没有定义它,仍然不起作用(。或者,如果我需要自己定义一个,最好的方法是什么?

简单编译命令:

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

我还尝试了来自以下的 Makefile:mingw32/bin/ld.exe ...对 [类] 的未定义引用...collect2.exe:错误:ld 返回 1 个退出状态

我通过以下方式检查了工具链依赖关系:Makefile:如何正确包含头文件及其目录?

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

尝试:

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

如果定义在 cpp 文件中,我会收到与您相同的错误。

头文件中是否有MyClass构造函数和析构函数定义(如指定的那样(?您是使用 Makefile 还是只尝试通过终端执行 g++? 链接器需要编译MyClass的对象。如果将 main.cpp 编译为整个可执行文件,它应该包含所有声明的定义。

看起来你得到了答案,但为了好习惯,你必须在 yourclass.hpp 中定义你的类和 cpp 文件中的实现,对于 main,你必须启动类对象,因为 main 函数获得正确的链接文件,即使项目中有多个文件。我希望它对你有用。

  1. 类定义:

    /*-------------------Myclass.h-------------------------*/
    class Myclass{
    private:
    //private member just for the exapmle
    int number;
    public:
    //Default constructor
    Myclass();
    //Parametrized constructor for any parametre it's just an example
    Myclass(const int n);
    //Destructor
    ~Myclass();
    //here you define your class's functions as it's public or private ...
    void Mymethod();
    };
    
  2. 类实现:

    /*-------------------Myclass.cpp-------------------------*/
    #include <iostream>
    #include "Myclass.h"
    //constructor
    Myclass::Myclass()
    {
    std::cout << " this is the default constructor"<< std::endl;
    }
    Myclass::Myclass(const int n)
    {
    std::cout << " this is the parametrized constructor"<< std::endl;
    number = n;
    }
    //destructor
    Myclass::~Myclass()
    {
    std::cout << " this is the default destructor"<< std::endl;
    }
    
    //method 
    void Myclass::Mymethod()
    {
    std::cout << " this is the function to perform within this class" 
    <<std::endl;
    }
    
  3. 主程序:

    #include "Myclass.h"
    //default constructor
    Myclass _class;
    //parametrized constructor
    Myclass _pclass(10);
    //here you must have the correct link to enter the main function
    int main (int argc, char** argv)
    {
    //here you call the desire function from your class 
    _class.Mymethod();
    }
    
  4. 汇编

    g++ Myclass.cpp Mymain.cpp -o Myexec
    

最新更新