Each .cpp is a translation unit. Basically, you should put each class
into a single .cpp file, and make sure each .cpp file has appropriate .h
file.
A translation unit roughly consists of a source file after it has been
processed by the C preprocessor, meaning that header files listed in
#include directives are literally included, sections of code within #ifdef
may be included, and macros have been expanded.
If you just want a function or variable visible to only current translation
unit. You can declare it as static. You don’t need put it into a header
file. But in C++, you have to put function definition or variable before
it use. Different with C language, In C language, compiler will guess a
function prototype from it’s usage, It’s not good sometimes.
C/C++ is separate compilation. If you need to use a function or
variable in two different files, you should put them in the #include .h
file. (add extern keyword before variable name). It will keep declaration
just once, DO NOT copy declaration to the other positions inthe .cpp file. It will lead to two or more copies, it’s bad smellof code.
A better suggestion is to have a single global.h file for a complex system.
Then put some common type, define, constant , global function in this
single global.h file. So it will help to reduce duplication, just keep once
appearance.
use #progma once to include guard, It’s not standard, but It has been
supported by many compiler. Including gcc and MSVC.
Three rules about header file:
Put your local/private header file in front of systemheader file. . Why? There are two advantage, 1) You can know
what header file should be included, It’s helpful to achieve the goal
of demand 2. 2) Some times, if you have you own fun with same
name as system or library, It can give you a compile error; Below
example will give you a compile error. But if you put <cmath>
before myHead.h. Then, main will use acos in cmath, and your
acos will be override.
You will need to put he minimal set of #include statements that are
needed to make the header compilable when your local/private header
is included on the first place.
Removing (or not adding in the first place) useless include statements.
If all you have are references or pointers to a class, you don’t need to
include that class’s header file; a forward reference will do nicely and
much more efficiently.
Change order of including order in .cpp file to avoid include another header
file in current head file. (This is only ad-hoc way, not a good code style.)
In .h file, you can include template and inline function. In fact, you
have to put template into .h file. and put a semicolon in theend of head file is good suggestion. You also need semicolon
after declare class. In .cpp file, no semicolon after each function
definition.