提问者:小点点

在编译时显示未定义的引用


我正在使用一个Sublime的文本编辑器和GNU编译器来做这件事。。。。 我已经在这三个文件中以相同的层次级别创建了这个。 还是不知道为什么它会表现出来。。。。

c:/mingw/bin/../lib/gcc/mingw32/9.2.0/../../../../mingw32/bin/ld.exe C:\Users\BIVASH~1\AppData\Local\Temp\cc1guWsB.o:Class.cpp:(.text+0xc): undefined reference to `speak()'
c:/mingw/bin/../lib/gcc/mingw32/9.2.0/../../../../mingw32/bin/ld.exe: C:\Users\BIVASH~1\AppData\Local\Temp\cc1guWsB.o:Class.cpp:(.text+0x11): undefined reference to `jump()'
collect2.exe: error: ld returned 1 exit status```

cpp类

#include <iostream>
#include "Cat.h"

using namespace std;

int main()
{
    speak();
    jump();
    return 0;
}

类别H

#ifndef CAT_H
#define CAT_H
void speak();
void jump();
#endif

cat.cpp


#include <iostream>
#include "Cat.h"
using namespace std;

void speak(){
    cout<<"mmmeeeeoooowwww!!!!";
}
void jump(){
    cout<<"jump jump jump !!!!!";
}

共1个答案

匿名用户

当你想要使用在一个不同的编译单元上写的函数时,你必须链接到另一个单元的对象文件。

要做到这一点,只包含其他单元的头是不够的,因为它只提供函数的声明。 为了得到定义,您应该将这两个单元编译在一起。 例如,对于foo.cpp和bar.cpp:g++foo.cpp bar.cpp

在你的情况下,只需写:

g++ Class.cpp Cat.cpp