Why should I not include cpp files and instead use a header?

Viewed 37256

So I finished my first C++ programming assignment and received my grade. But according to the grading, I lost marks for including cpp files instead of compiling and linking them. I'm not too clear on what that means.

Taking a look back at my code, I chose not to create header files for my classes, but did everything in the cpp files (it seemed to work fine without header files...). I'm guessing that the grader meant that I wrote '#include "mycppfile.cpp";' in some of my files.

My reasoning for #include'ing the cpp files was: - Everything that was supposed to go into the header file was in my cpp file, so I pretended it was like a header file - In monkey-see-monkey do fashion, I saw that other header files were #include'd in the files, so I did the same for my cpp file.

So what exactly did I do wrong, and why is it bad?

14 Answers

There are times when non conventional programming techniques are actually quite useful and solve otherwise difficult (if not impossible problems).

If C source is generated by third party applications such as lexx and yacc they can obviously be compiled and linked separately and this is the usual approach.

However there are times when these sources can cause linkage problems with other unrelated sources. You have some options if this occurs. Rewrite the conflicting components to accommodate the lexx and yacc sources. Modify the lexx & yacc componets to accommodate your sources. '#Include' the lexx and yacc sources where they are required.

Re-writing the the components is fine if the changes are small and the components are understood to begin with (i.e: you not porting someone else's code).

Modifying the lexx and yacc source is fine as long as the build process doesn't keep regenerating the source from the lexx and yacc scripts. You can always revert to one of the other two methods if you feel it is required.

Adding a single #include and modifying the makefile to remove the build of the lexx/yacc components to overcome all your problems is attractive fast and provides you the opportunity to prove the code works at all without spending time rewriting code and questing whether the code would have ever worked in the first place when it isn't working now.

When two C files are included together they are basically one file and there are no external references required to be resolved at link time!

Related