1

for example, in A.h:

class A{
   void method();
};

and in A.cpp:

#include "A.h"

void A::method(){/*do stuff*/};

and in main.cpp

#include "A.h"

int main(){
   A a;

   a.method();
}

How do I access the definition of the method from A.cpp by including only A.h in my main.cpp file? Is there a trick involving makefiles or IDEs?

7
  • 1
    What you are asking for is something a code editor would implement, so look at the features of whichever code editor you are using to write your code with. Commented Dec 28, 2015 at 19:37
  • I'm using Xcode. I don't know what this kind of feature is called so I don't know what to look up. Commented Dec 28, 2015 at 19:44
  • At what point does your example require the "definition of the method"? Commented Dec 28, 2015 at 19:56
  • 1
    You would need to make the declaration of 'method' ( in the .h file ) a public member method as C++ member methods are private by default. Commented Dec 28, 2015 at 20:09
  • What exactly are you trying to achieve? are you getting an error message? Commented Dec 29, 2015 at 14:10

2 Answers 2

4

Is there a trick involving makefiles or IDEs?

This "trick" called linking - loading all compiled modules and libraries together into executable file. In your case you can do that manually:

g++ -c a.cpp -o a.o  // compiling a.cpp and producing object file a.o
g++ -c main.cpp -o main.o // compiling main.cpp and producing object file main.o
g++ main.o a.o -o myprog // linking all object files together with system libraries and producing executable myprog

For different compilers commands may look different, but process is the same. Of course you do not want to type all of that again and again so you would want to automate that. That what IDE or makefile does for you, there are no tricks or magic involved.

Sign up to request clarification or add additional context in comments.

4 Comments

@user3063750 in IDE (including Xcode) usually you have a project - each .cpp file included into project is compiled and linked together.
So doesn't that mean the example I have should work? I'm still getting an "Undefined symbols for architecture x86_64" error.
@user3063750 my telepathy machine broke yesterday, I am waiting for it to be fixed. sorry.
The example I had in the question. If you have a scroll-wheel machine, you can probably find it directly north of here.
0

I figured it out by adding a new .cpp file to the project which is automatically linked to a corresponding .hpp file by Xcode.

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.