创建类链接错误

creating classes link error

本文关键字:错误 链接 创建      更新时间:2023-10-16

我正在使用 Dev-C++ 5.2.0.1

我举了一个如何将类放在网站的另一个文件中的示例,但它导致了错误。

在文件类.h中,我有:

class MyClass
{
public:
  void foo();
  int bar;
};

在文件类中.cpp我有:

#include "class.h"
void MyClass::foo()
{
    cout<< "test";
}

在文件主中.cpp我有:

#include "class.h" 
using namespace std;
int main()
{
  MyClass a;
  a.foo();
  return 0;
}

这是我得到的错误: [链接器错误]C:\Users\Matthew\AppData\Local\Temp\cccWe7ee.o:main.cpp:(.text+0x16): 对'MyClass::foo()' 的未定义引用 收集2:LD 返回 1 个退出状态

我做错了什么吗?

新答案。

您是否正在编译所有文件并将其链接在一起?在 gcc 中,您可以执行以下操作:

gcc -o myExe class.cpp main.cpp

我对 dev-c++ 不太确定,但我想它没有太大区别。

foo() 只有定义。如果要使用没有实现的函数,Linker 会给你此错误"未定义的引用"。

相关文章: