【发布时间】:2020-01-24 11:28:03
【问题描述】:
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?
【问题讨论】:
-
确定您的代码可以编译吗?此行中分号已关闭:
~MyClass() {cout << "Destructor definition instead of g++ default one?"} ;应该是:~MyClass() {cout << "Destructor definition instead of g++ default one?";} -
抱歉打错了,我更正了
-
抱歉,我无法重现您的问题。尝试提出一个产生错误的最小可编译示例。
-
好的,我今天就来个小例子,谢谢
-
如您在此处看到的:onlinegdb.com/rkbWuIu-L 它可以正常运行和编译。
标签: c++ gcc linker g++ destructor