0

I came across this implementation of some code which requires us to create a header and then #include it in our source code. So my question is why we need to create a .cpp file along with the .h and what all compilations we should to in order to use the header file in a test program

  • Voting to close as "too broad", since there's not enough information to tell specifically what you're trying to ask. – user253751 Nov 17 '15 at 03:51

1 Answers1

0

If your program is small enough that it's reasonable to put the whole thing in a single .cpp file, you don't really need a header file. But larger programs are usually divided into multiple .cpp files, and header files are used for code that needs to be included in more than one .cpp file.

Even in a multi-file project, headers aren't strictly necessary — you could just copy-and-paste things like class definitions and function declarations into each .cpp file that needs them. But they have to match exactly, which means that whenever you wanted to change one of those things, you'd have to find all the copies and change them all in the same way, which is extremely inconvenient and very prone to mistakes. Using #include lets you keep a single copy of that code in a header file, instead of having to put duplicate copies into lots of .cpp files.

Wyzard
  • 33,849
  • 3
  • 67
  • 87