正确包含文件,但仍然出现链接器错误

Including files correctly , but still getting linker error

希望你们一切顺利。我只是在 C++ 中遇到链接器错误,我不知道为什么?一切都是正确的...... 检查下方 testing.h 文件


#ifndef __MYClass__
#define __MYClass__
#include<iostream>
using namespace std;
class Abc {
private:
    int a;
public:
    void input();
    void display();
};


#endif


这里是 Functions.cpp 文件中这些函数的实现。


#include"testing.h"

void Abc::input() {
    cout<<"Enter any value : ";
    cin>>a;
}
void Abc::display() {
    cout<<"You Entered : "<<a;
}

而现在,在 main.cpp

#include<iostream>
#include"testing.h"
using namespace std;
int main() {
    Abc obj;
    obj.input();
    obj.display();
    return 0;
}

所有文件编译成功。 在 main.cpp 链接器说.... g++ -Wall -o "main" "main.cpp" (在目录中:/home/Welcome/C++ Practices/testingLinux) /usr/bin/ld: /tmp/ccYI9LAy.o: 在函数 main': main.cpp:(.text+0x10): undefined reference to Abc::input()' /usr/bin/ld: main.cpp:(.text+0x1c): 未定义对 `Abc::display()' 的引用 collect2:错误:ld 返回 1 退出状态 编译失败。 我正在使用内置 linux 编译器...

您没有编译 Functions.cpp 文件。
这应该可以解决您的问题:

g++ main.cpp Functions.cpp

有多种方法可以解决此问题,但在此之前请阅读 Translation Unit

解决您的问题。

写的时候

g++ -Wall -o main main.cpp

编译器将选择 main.cpp 进行编译并扩展 testing.h,其中包括 声明 用于 class ABC 以及此头文件可以确定 ABC 的大小,并能够生成在堆栈上为 obj 保留 space 的指令。它看不到 input()display() 的定义,因此将该任务推迟到 link 人。请注意 testing.cpp 根本不在图片中 因为编译器不知道 ABC 的实现在 testing.cpp 中。现在,当 linker 尝试解析符号 input() 时,它找不到 定义 并抛出错误

undefined reference to Abc::input()

因此,要解决此问题,您可以预先明确告诉它在编译 main.cpp 时还需要接受 testing.cpp by

g++ -o main main.cpp testing.cpp

另一种方法是从 testing.htesting.cpp

中创建一个 动态库
g++ -shared -fPIC testing.cpp -o libtest

然后 link 它反对 main.cpp

g++ -o main  main.cpp -I. -L. libtest

这样做的是,编译器仍然无法弄清楚 input()display() 但是 的 linker 的定义可以从现在开始提供包含 定义 的库。