Header File (C++)
https://www.learncpp.com/cpp-tutorial/header-files/ https://www.cs.odu.edu/~zeil/cs333/f13/Public/faq/faq-htmlsu21.html
A .h
file contains shared declarations, a .cpp
file contains definitions and local declarations. This is basically doing Forward Declaration.
Question
What is the point of declaring in the header file if you reuse it in the
.cc
file? Well If you have multiple.cc
files, where one calls the function of another file, how do you import the function? You need the header file…Also,
.h
files help with more readable code, more efficient for the compiler, and is needed in cases of cyclical dependencies, see Forward Declaration (hmm i’m not sure about this last one anymore).
It’s important that you understand the difference between declarations and definitions.
- A
.h
file is intended to be#include
d from many different .cpp
files that make up a single program - (IMPORTANT) The Preprocessor actually replaces each
#include
by the full contents of the included.h
file. Consequently, a .h
file may be processed many times during the compilation of a single program, and should contain should contain only declarations. - A
.cpp
file is intended to be compiled once for any given build of the program. So the.cpp
file can have any declarations that it doesn’t need to share with other parts of the program, and it can have definitions. But the main purpose of a .cpp file is to contain definitions that must only be compiled once. The most common example of this would be function bodies.
NEVER do this
Never, ever, ever name a
.cpp
file in an#include
. That defeats the whole purpose of a C++ program structure..h
files are#include
d;.cpp
files are Compiled.
A typical program will consist of many .cpp
files.
.h
vs.hpp
?
.h
can be both a C and a C++ file. This is why if you are working in C++, it is better to use.hpp
.
What is difference between
#include <filename>
and#include "filename"
?
#include <filename>
The preprocessor searches in an implementation-defined manner, normally in directories pre-designated by the compiler/IDE. This method is normally used to include header files for the C standard library and other header files associated with the target platform.#include "filename"
: The preprocessor also searches in an implementation-defined manner, but one that is normally used to include programmer-defined header files and typically includes same directory as the file containing the directive (unless an absolute path is given).