I have a question about source file and header in c++.
I have a header which is used to declare the functions. And I implement these functions in C++.
Now I need to use these functions in other files. Should I include both source file and header file in order to use these functions?
The basic compilation model used by (C and) C++ is thus:
#includedirectives with the file(s) included. The result is called a compilation unit.In C++, this is often a bit more complicated in practice (especially due to inlining and templates, but also with features like link-time code generation), but that’s the basic principles.
The implications of that are:
Since the whole preprocessor magic is just a simple text replacement engine without any knowledge of (C or) C++ and about its purpose in the process described above, it can be bend and and abused to do other things. In this, including source files has been done sometimes to achieve some goal. But it’s rare.
If a linker can’t find a symbol that has been declared (and thus references to it have been accepted by the compiler), it will spit a nasty error message into your face. If it finds multiple definitions it will do likewise.
However, if you write declarations directly into source files, the compiler, not being able to “look” into other translation units, can’t warn you that they are out of date. If you put declarations into header files instead, it is much easier to keep them in sync with their corresponding definitions, and often the compiler can even diagnose if they don’t match.
If you change a header that is, directly or indirectly, used in many source files, you will have to re-compile most of your project. If you change a source file, you will only have to re-compile that one source files (and re-link the executable, of course).