【问题标题】:undefined reference to "***" [duplicate]未定义对“***”的引用[重复]
【发布时间】:2019-01-28 09:00:21
【问题描述】:

我在 Cat.h 文件中定义了一个类 Cat,它有一个成员函数 void Cat::miao()。然后,我在 Cat.cpp 中实现了这个函数,代码如下。

但是,在编译和链接时,我得到了一个错误,比如“未定义对`Cat::miao()的引用”。代码有什么问题?

我的编译器是 GNU c11。

-----猫.h

#include<iostream>
#include<string>
using namespace std;
class Cat
{
    string name;
    public:
        Cat(const string&n):name(n){};
        void miao();
};

-----Cat.cpp

#include"Cat.h"
void Cat::miao()
{
    cout << name << endl;
}

-----main.cpp

#include"Cat.h"
int main()
{
    Cat tom("tom");
    tom.miao();
    return 1;
}

编译:

g++ main.cpp

导致此错误:

C:\Users****:K.o:main.cpp:(.text+0x69): 未定义对 `Cat:: 的引用 喵()' collect2.exe:错误:ld 返回 1 个退出状态

【问题讨论】:

  • 这看起来像是一个链接问题 - 你能粘贴用于编译(/链接)你的程序的确切命令吗?
  • Windows 8 中的命令“g++ main.cpp”
  • 你没有编译Cat.cpp。试试g++ main.cpp Cat.cpp
  • @W.Cameron 您需要添加cat.cpp,例如g++ main.cpp cat.cpp
  • @W.Cameron 检查答案是否可行。

标签: c++ c++11 linker


【解决方案1】:

在编译过程的最后链接部分,Cat.cpp 没有正确链接到 main.cpp。

使用命令g++ main.cpp 编译将尝试编译和链接main.cpp。 Cat.cpp 没有被编译并链接到 main.cpp,因为您没有在命令行中指定它的名称。

可能的修复:编译时使用g++ main.cpp Cat.cpp

如果您打算制作一个大型项目,还建议您设置一个 Makefile 或其他构建管理器,但如果您只是为了教程而这样做并且打算在 5 分钟内丢弃此代码,这是不需要。

【讨论】:

  • 是的,你绝对正确。我尝试命令“g++ main.cpp cat.cpp”,它可以工作。
【解决方案2】:

试试这个

-----猫.h

#include<iostream>
#include<string>
using namespace std;
class Cat
{
    string name;
    public:
        Cat(const string&n):name(n){};
        void miao();
};

-----Cat.cpp

#include"Cat.h"
void Cat::miao()
{
    cout << name << endl;
}

-----main.cpp

#include"Cat.h"
int main()
{
    Cat tom("tom");
    tom.miao();
    return 1;
}

编译:

g++ main.cpp  cat.cpp

肯定会奏效的。

【讨论】:

    猜你喜欢
    • 2011-07-27
    • 2013-06-20
    • 2012-02-05
    • 2014-12-27
    • 2012-11-15
    • 2022-01-16
    • 2017-01-26
    • 2016-10-11
    相关资源
    最近更新 更多