这是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/