The make updates a target e.g myprog that depends on prerequisite files myprog.cpp myprog.h if any of the prerequisite files have been modified or the target doesn't exist.
Rules of a makefile
By default, make starts with the first target, thus make with no arguments , reads the makefile in the current directory and processes the first rule
But before make can process this rule, it must check if the prerequisite files depend on other files, and process the rules for them
If some other rule is not depended on by the goal, that rule is not processed, unless you tell make to do so, e.g. make clean
Here the makefile will start with the target sum. Since sum is dependent on main.o and sum.o it will go to them first.
The target main.o will check for main.cpp and sum.h. Afterward it will run g++ –c main.cpp and compile main.o
The clean target isn't dependent on sum and if we were to run it we will type in make clean
Makefile Variables
To clean up our code we can use variabeles. To delcare a variable type var_name = my_var and to use them just use the dollar sign $(var_name).
For example:
Here we declared and used 4 different variables: OBJFILES, PROGRAM, CC and CFLAGS.
Exercise
Create a makefile for the following files: main.cpp, Point.cpp, Point.hpp, Rectangle.cpp, Rectangle.hpp, Circle.cpp Circle.hpp, Triangle.cpp Triangle.hpp. Rectangle, Circle and Triangle are all dependent on Point
Special Symbols
Let say we have the following makefile
$@ evaluates to all
$< evaluates to library.cpp
$^ evaluates to library.cpp main.cpp
Example 1: Naive
The -I. is included so that gcc will look in the current directory (.) for the header files. More examples can be found here.
Let explain the following rule
The rule says that the .o file depends upon the .c version of the file and the .h files included in the DEPS macro. The rule then says that to generate the .o file, make needs to compile the .c file using the compiler defined in the CC macro.
The -c flag says to generate the object file. the -o stands for output and -o $@ says to put the output of the compilation in the file named on the left side of the : e.g. hellomake The $< is the first item in the dependencies list
Bash and Makefiles
Lets say that we only have main.cpp, makefile and a s.sh