【问题标题】:mingw32/bin/ld.exe ... undefined reference to [class] ... collect2.exe: error: ld returned 1 exit statusmingw32/bin/ld.exe ... 未定义对 [class] 的引用 ... collect2.exe:错误:ld 返回 1 退出状态
【发布时间】:2020-05-06 18:30:24
【问题描述】:

我尝试将代码从 Linux 移动到 Windows 时的问题描述:

  • MinGW 上的 Windows 链接器问题
  • 当我在 Main.cpp 中调用用户定义的类时发生 (如果我不在 Main 中调用用户定义的类构造函数,则可以正常工作)

相关代码示例:

Person.hpp

class Person
{
    public:
        Person(const string& iName, 
                const list<string>& iContactDetails,
               ); 

        virtual ~Person(); 
        ...

Main.cpp

#include "Person.hpp"
...
int main()
{
...
Person myPerson = Person (myName, myContactDetails); //here is the linker problem
...
return 0;
}

编译命令:

独立

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

Makefile(甚至尝试使用 CC 代替 CXX,或 LDFLAGS=-lgdi32 代替 CXXFLAGS)

EXECUTABLE = MyProgram.exe

CXX = "C:\MinGW\bin\g++.exe"
CXXFLAGS = -Wall      // tried LDFLAGS=-lgdi32 as well

src = $(wildcard *.cpp)
obj = $(src:.cpp=.o)

all: myprog

myprog: $(obj)
    $(CXX) -o $(EXECUTABLE) $^ $(CXXFLAGS)

.PHONY: clean
clean:
    del $(obj) $(EXECUTABLE)

错误:

c:/mingw/bin/../lib/gcc/mingw32/8.2.0/../../../../mingw32/bin/ld.exe: C:\Users\....:Main.cpp:(.text+0x124c): undefined reference to `Person::~Person()'
collect2.exe: error: ld returned 1 exit status

总结一下,我在MinGW G++编译步骤中遇到了Linker问题:

所有外部实体引用均已解析。库组件是 链接以满足对未在 当前翻译。所有这样的翻译输出都被收集到一个 程序映像,其中包含执行所需的信息 执行环境。

我尝试关注其他类似的问题,但不幸的是它们是不同的问题:

  1. C compiler error: undefined reference to function
  2. What is an undefined reference/unresolved external symbol error and how do I fix it?
  3. facing error in linking codes in c++

我应该如何更改我的 Makefile 或我的代码? MinGW 在 Windows 中使用哪些标志?非常感谢

【问题讨论】:

  • 那么,在您看来,析构函数的代码在哪里?编译器能看到吗?例如不在显示的代码中。
  • 链接 2.,接受的答案,列表中的第二个链接,第四个代码块。
  • 实际上,在链接中有一个触发此链接错误的原因列表。在我们的例子中,它应该是:stackoverflow.com/questions/12573816/… 不过,我不知道如何更改 Makefile 以引用 Person 类?

标签: c++ gcc linker g++ mingw


【解决方案1】:

与我为 How to correctly define and link a C++ class destructor to a main file? 提供的答案相同

我和你有同样的问题。尝试将您的构造函数和析构函数定义从 cpp 移动到头文件中。这样,仅通过运行您提到的简单 g++ 命令即可很好地完成链接,您不需要 Makefile。包含告诉您的编译器在哪里可以找到定义。

试试:

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

如果定义在 cpp 文件中,我会得到和你一样的错误。

猜你喜欢
  • 2018-05-04
  • 2013-06-01
  • 2014-09-03
  • 2021-08-04
  • 2021-02-07
  • 2020-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多