Help with classes not being able to call functions.

Hi, So I wrote a simple program and tried to call a function from a class outside of the main file. When the class is in the main file the program runs fine. Can you help?
1
2
3
4
5
6
7
8
9
//in main.cpp
#include "myclass.hpp"  // defines MyClass

int main()
{
  MyClass a; // no longer produces an error, because MyClass is defined
  a.foo();
  return 0;
}


the class:
1
2
3
4
5
6
// in myclass.cpp
#include "myclass.hpp"

void MyClass::foo()
{
}


the header file:

1
2
3
4
5
6
7
8
// in myclass.h

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

and yes I pulled the code off of the article on this site, but it's the same problem I have with my program.
What exactly is the problem you are having?
C:\Users\Cayle\AppData\Local\Temp\ccn4zg2n.o:main.cpp:(.text+0x15): undefined reference to `MyClass::foo()'
collect2.exe: error: ld returned 1 exit status
It seems like your class is not being linked properly is your header filer a .h or .hpp you are including a .hpp but your comments suggest it is a .h.

Also that second error means you never closed the old one before trying to open a new one..Maybe try and close the old and compile/build/run a new one. The code you posted though should work.
All of my files are .cpp/.hpp the second error went away as you said. I tried changing the header to .h and the same error still came up.
Last edited on
Topic archived. No new replies allowed.