Understanding C++ Makefile
A Makefile is a simple text file that contains a set of rules for building an executable program from source code files. Each rule specifies a target (the executable or object file being built), the dependencies (the source files that the target depends on), and the commands that are used to build the target from the dependencies.
In C++, Makefiles are typically used to build and link multiple source files together into a single executable program. The Makefile contains a rule for each source file, specifying the object file that will be created from the source file and the dependencies (i.e., other source files) that the object file depends on. The Makefile also contains a rule for the final executable, specifying the object files that it depends on and the linker command that will be used to create the executable.
The make program reads the Makefile and uses it to determine what needs to be built and in what order. It checks the timestamps of the files and only rebuilds targets that are out-of-date. This makes the build process more efficient, as it only rebuilds the parts of the program that have changed.
Suppose you are making a program called Project
that has following files inside it:
Project:
|-----project.cc
|
|-----point.h
|-----point.cc
|
|-----fraction.h
|-----fraction.cc
The project’s main file is project.cc (with main
function) which depends on point.cc
which in turn depends on fraction.cc
.
The make file to execute this program would be:
project: project.o point.o fraction.o
g++ -std=c++11 -o project project.o point.o fraction.o
project.o: project.cc point.cc
g++ -std=c++11 -c project.cc
point.o: point.cc point.h
g++ -std=c++11 -c point.cc
fraction.o: fraction.cc fraction.h
g++ -std=c++11 -c fraction.cc
The make file has four main rules.
The first declares the name of the target/executable i.e. project
and it’s dependencies. The second line is the command used to create that target; it specifies the C++ standard used and the objects file to be built. [g++ -std=c++11 -o project project.o point.o fraction.o
]
The other rules follow the similar pattern as first. Only difference is that they specify other targets/executables [ project.0, point.o, fraction.o
] to be built in order run the main executable file, and the command used to built each of these object file. eg. g++ -std=c++11 -c project.cc
Important: the space before g++
in the make file must be a Tab not space(s). You might have to configure your IDE in order for the compiler to see those spaces as Tab.
Once the make file is ready. You just need to run make
in order to run the Makefile. After you run the make
command you should see something like below:
Note the object files and the executable project
in red created after running the make file.