While following the book C For Dummies, I have three files in my CodeBlocks project, main.cpp, Pen.h, and Pen.cpp. They look like this:
main.cpp:
#include <iostream>
#include "Pen.h"
//#include "Pen.cpp"
using namespace std;
int main()
{
Pen MyPen = Pen();
MyPen.test();
}
Pen.h:
#ifndef PEN_H_INCLUDED
#define PEN_H_INCLUDED
//#include "Pen.cpp" // Uncommenting this gives a different error
using namespace std;
class Pen
{
public:
// attributes omitted
// PROTOTYPES:
// other functions omitted
void test();
};
#endif // PEN_H_INCLUDED
Pen.cpp:
#include <iostream>
#include "Pen.h"
using namespace std;
//other function definitions omitted
void Pen::test()
{
cout << "Test successful." << endl;
}
When I run the code as listed above, I get an "undefined reference to `Pen::test()'" error. To fix this, I changed the #include statements at the top of main.cpp to:
#include <iostream>
//#include "Pen.h"
#include "Pen.cpp"
This works as intended and correctly prints out "Test successful."
My question is this: what in the world is the point of putting a function prototype in a header file if I have to import the .cpp file later on anyways?
My original understanding of header files was that you could use them to keep class definitions in a separate file so that you don't have one extremely long file for the whole program.
Then, when I learned you can put a function prototype in one file and define the function later, I figured that was to help make the header more readable.
However, I can't import only the header file, since it fails to compile. I have to import the .cpp file anyway. On top of that, commenting out the import for the header file in main.cpp doesn't do anything, so what in the world is the point of having a header file if it just acts like an unnecessary middleman? Why not just always use .cpp files, with prototypes at the top?
CodePudding user response:
Assuming you're using gcc, you can compile and link in one step by supplying multiple .cpp files via the command line.
g Pen.cpp main.cpp
clang should be similar.
clang Pen.cpp main.cpp
An #include should never reference a .cpp file. At all. There's no good reason to do it. Include your headers and then supply the names of all .cpp files when you compile. If your project gets big and you have too many .cpp files to reasonably list, then it's time to break out a makefile or similar.
CodePudding user response:
In the main.cpp include the header file:
#include "Pen.h"
The Pen.h file it's ok.
You need to add the Pen.cpp file to the project tree.
Go to Project -> Add files... and add Pen.cpp

