.cpp
- source file.h
- header file.o
- object fileprog
- executable file/taget file
Key word: extern
eg,extern int b;
This is an non-local decorator, compiler goes to other soure files to search the variable b
.
How to do modularization for different cases?
Regular case
Header guard
#include "headerfile"
can’t be duplicated in any two related files.
Solution:
In c.h
file, define
1 |
|
No matter which file defines this header file, if duplicated then just ignore instead of error.
Circular dependencies
Solution: pre-prototype, using For
decoration, define class F
in E.h
and define class E in f.h
. Then the compiler knows class F
wil be defined later in F.h
and class E
will be defined later in E.h
.
Watch out:
- Never place
using namespace
in header file, which is only used in source code(.cpp
). - never palce
using namespace
before#include
.
Difference bettween #include "•"
and #include <•>
#include "•"
: indicates a path is provided to locate the header file.#include <•>
: indicates that the header file is located in the default library locations defined in the enviromental variables, in IDE settings or operation settings.
Compile methods
simple struct of compile files
more complicated: makefile
make
is a Linux command
Some options:
- -g - turn on debugging (so GDB gives more friendly output)
- -Wall - turns on most warnings
- -O or -O2 - turn on optimizations
- -o
- name of the output file - -c - output an object file (.o)
- -I
- specify an include directory - -L
- specify a lib directory - -l
- link with library lib .a
Simplify makefile
- remove abvious dependency
- only keep one line of build rule, other same build rules are redundant
- omit target name which is duplicated
The cleanest version is:
Advanced version
Build compile rule with self-define variables
Caution: be careful TAB, space is not necessary, which is just for better formatting.
For example:
1 | CXX = g++ // CXX is self-defined variable, and g++ is the value. This line is to define the compiler tool |
If we want to make change to the content of building rule, just change the value of the variables instead of changing rules, because the building rule is generally provided in large project by company
Evolutionary version
Adding auto dependency
1 | CXX = g++ |
Run command
make
- compile whole project by makefile, which refers to default implementation in Linux. gmake
- compile whole project by makefile, which refers to Gun make in Unix. make clean
- execute clean
line of makefile.
Reference material:
Book: Thinking in C++, Volume 1, 2nd Edition, Bruce Eckel.
Lectures: University of Waterloo, CS 247 (Software Abstraction and Specificati), 2020 spring term, professor Scott Chen.