But when I compile it, it says:
./obj/PE.o: In function `PE::problemEleven()':
PE.cpp:(.text+0x0): multiple definition of `PE::problemEleven()'
./obj/main.o:main.cpp:(.text+0x0): first defined here
collect2: ld returned 1 exit status
Compilation failed.
make: *** [all] Error 1
So I was just wondering if I'm including things or putting class definitions wrong somewhere, and if I am, why I can't do it this way? It seems to me that .hpp has some stuff, and so I can include it in .cpp, and then main can include the .cpp so that it has everything it needs, but apparently there's something more subtle going on here?
By including PE.cpp in main.cpp, you now have the definition of problemEleven in two different translation units: main.cpp and PE.cpp.
You only include header files, which are the files that contain the declarations - not the .cpp files.
Hi Athar,
Thanks for your response. So now I have my main include the .hpp, and I moved the class declaration to the .hpp, while my functions remain in .cpp and everything works fine.
But now my question is: if I only include .hpp in main, how does main see my .cpp file? It seems to a newbie like me that main.cpp will only be able to see the class declaration, as well as acknowledge that the methods in the class exists, but how would it go about actually executing the method? Rather, if I only include .hpp in my main, how come it isn't blind to the .cpp file?
But now my question is: if I only include .hpp in main, how does main see my .cpp file? It seems to a newbie like me that main.cpp will only be able to see the class declaration, as well as acknowledge that the methods in the class exists, but how would it go about actually executing the method? Rather, if I only include .hpp in my main, how come it isn't blind to the .cpp file?
That's where linking comes into play.
When compiling main.cpp, the compiler only knows that the method probably exists somewhere, like you said.
So it generates a call to said function, but since it doesn't know anything about it, the call is just a placeholder.
After compiling, the object files generated by the compiler are passed to the linker.
It will see that main.cpp has an unresolved reference to "problemEleven" and will search for a definition in any of the object files. If it can find it, the placeholder call will be replaced with the actual location of the function. If it can't find it, you'll get an "undefined reference" linker error. And if it finds multiple definition of the same symbol, you'll get the error you originally had.