creating classes link error

2019-02-28 17:16发布

I'm using Dev-C++ 5.2.0.1

I took an example of how to put a class in another file from a website but it resulted in an error.

In the file class.h I have:

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

In the file class.cpp I have:

#include "class.h"

void MyClass::foo()
{
    cout<< "test";
}

In the file main.cpp I have:

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

Here is the error I get: [Linker error] C:\Users\Matthew\AppData\Local\Temp\cccWe7ee.o:main.cpp:(.text+0x16): undefined reference to `MyClass::foo()' collect2: ld returned 1 exit status

Is there something I'm doing wrong?

标签: c++ class
2条回答
等我变得足够好
2楼-- · 2019-02-28 17:44

foo() only have definition. If you want to use a function that doesn't have a implement, Linker will give you this error "undefined reference".

查看更多
来,给爷笑一个
3楼-- · 2019-02-28 17:57

New answer.

Are you compiling and linking all of your files together? In gcc you would do something like:

gcc -o myExe class.cpp main.cpp

I'm not so sure about dev-c++, but I imagine it's not much different.

查看更多
登录 后发表回答