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

标签 c++ gcc linker g++ destructor

这是mingw32/bin/ld.exe ... undefined reference to [class] ... collect2.exe: error: ld returned 1 exit status中的一个特定问题

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

我也尝试过来自mingw32/bin/ld.exe ... undefined reference to [class] ... collect2.exe: error: ld returned 1 exit status的Makefile

然后我通过以下方式检查了工具链的依赖性:Makefile: How to correctly include header file and its directory?

最佳答案

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

尝试:

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

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

关于c++ - 如何正确定义C++类析构函数并将其链接到主文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59895532/

相关文章:

c++ - 更多 spirit 疯狂 - 解析器类型(规则与 int_parser<>)和元编程技术

c++ - 字符串在转换为 char* C++ 时被截断

c++ - 为什么 std::vector::insert 复杂度是线性的(而不是恒定的)?

c - 使用 mingw 对 imp 的 undefined reference

c - 使用条件标志作为 GNU C 内联 asm 输出

c++ - MS visual studio 2013 SDL 不工作

c++ - 在类方法中分配给二维数组

linux - autoconf 在 Linux Mint 上提示 "C compiler cannot create executables"

html - 服务器路径性能(绝对链接与相对链接)

c++ - googletest & cmake - 体系结构 x86_64 的 undefined symbol