I would like to know the difference between header (h) and source (cpp) files. We usually use headers for declaration and cpp s for definition of non-template stuff, and 2 different headers for declaration and definition with templates. Does compile even care whether the file is cpp or h? Isn't the only thing which he is doing is copying from one file to another with include directive? Does it matter from which type of file the text is being copied?
-
possible duplicate of [Why have header files and .cpp files in C++?](http://stackoverflow.com/questions/333889/why-have-header-files-and-cpp-files-in-c) – m.s. May 10 '15 at 13:44
-
Only source files get compiled. Only header files are intended to appear in multiple source files. – Drew Dormann May 10 '15 at 13:58
3 Answers
When you include a header file it will be inlined at compile time, meaning it probably has to have C++ content in it (unless the entire file be comments). From this point of view, .h
and .cpp
files are the same in that they both contain C++ code.
However, best practices dictate that .h
files be used for templating and class definitions, while .cpp
files are used for implementations and source code. It is bad practice to mix usage of the two although it is possible.

- 502,043
- 27
- 286
- 360
This is not a complete answer, but I provide some pointers. The C/C++ languages (or their preprocessors), strictly speaking, do not care for the most part -- the header files are there more for programmer convenience.
That said, the C/C++ Standards do specify the existence of the Standard library headers (not exactly "header files", though), e.g. <iostream>
and <cstdio>
.
What both languages do have firmly is the concept of "translation units", which are one or more units of compilation that are later linked together into the final program. In C++, there is also the One Definition Rule which affects what you can put in your header files vs. your .cpp files without them getting duplicated in your program.

- 1,111
- 11
- 10
I encountered the following case. Lets say you have two source file.
file1.cpp has main()
and file2.cpp has some helper function x()
and y()
. and file1.cpp has declaration for x()
and y()
it will compile and program will run. In case you defined the function in file2.h instead of file2.cpp and you didn't #include "file2.h"
then there will be compile time error undefiend reference to x(),y()
. For a declarations in .h
file if there are no definition in the same file the compiler will look for definition in a .cpp
file not a .h
file.

- 485
- 5
- 17