15

I am trying to implement a class in different cpp files. I understand it is a legitimate thing to do in C++ if the member functions are independent. However one of the member function uses another member function such as in this case:

In function1.cpp

#include "myclass.h"
void myclass::function1()
{ 
    function2();
}

In function2.cpp

#include "myclass.h"
void myclass::function2()
{
....
}

I will get an error of undefined reference to function2. It doesn't work by adding this pointer either. Do I need to declare it in some way in function1.cpp? Thanks~

The header file includes declaration of both functions. It works when function1 and function 2 are in the same file but not when I separate them. I also believe I've added both cpp in the project. I am using Qt creater btw.

5
  • have you declared both function1() and function2() in myclass.h? Commented Aug 4, 2011 at 10:38
  • You need to have the function declarations of both the functions in the header file (myclass.h). Commented Aug 4, 2011 at 10:38
  • Can you add your myclass.h file? Maybe some error with class declaration - because of those situation is ok, and error mustn't be here Commented Aug 4, 2011 at 10:39
  • 1
    Are you sure that both of the .cpp files are included in your compilation? Commented Aug 4, 2011 at 10:43
  • There is no problem with your approach. What's the actual compiler error? Commented Aug 4, 2011 at 11:25

3 Answers 3

16

As long as myclass.h contains the definition of the class with the declarations of the member functions, you should be fine. Example:

//MyClass.h
#ifndef XXXXXXXX
#define XXXXXXXX
class MyClass
{
  public:
   void f1();
   void f2();
};
#endif

//MyClass1.cpp
#include "MyClass.h"
void MyClass::f1()
{
};

//MyClass2.cpp
#include "MyClass.h"
void MyClass::f2()
{
     f1(); //OK
}
Sign up to request clarification or add additional context in comments.

2 Comments

hi thanks. I believe this is what I did. Still won't compile though. It works fine when the two functions are in the same file. I am working with Qt and both files are listed in the project.
this is not working.
2

This should work. If you get a linker error, make sure you compile both your cpp files, that's what's most probably causing your error.

Comments

1

Everything seems fine to me. There might be something wrong with your build process. You should compile the two .cpp files (using -c option) into object files and link them together in the next stage.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.