Makefile
A Makefile is a special file used to streamline and automate the build process of a software project. It simplifies compiling and linking code, helping to save time and minimize errors—especially in projects with multiple source files and complex dependencies.
Basic Concepts
A target is usually the name of a file that is generated by a program; examples of targets are executable or object files. A target can also be the name of an action to carry out, such as ‘clean’.
A prerequisite is a file that is used as input to create the target. A target often depends on several files.
A recipe is an action that make carries out. A recipe may have more than one command, either on the same line or each on its own line. Please note: you need to put a tab character at the beginning of every recipe line!
target … : prerequisites …
recipe
…
…
Symbols and Special Characters
- $@`: Represents the target name.
- $<`: Represents the first dependency.
- $^`: Represents all dependencies.
- .PHONY: Specifies that a target is not a file, but a label for a command.
Creating a Simple Makefile
Suppose we have function1.cpp, function2.cpp, main.cpp and functions.h
To compile this file, we would normally run:
Instead, we can create a Makefile to automate this process.
now we can run it as shown below:
Explanation:
cc = g++
This sets the variable cc to g++, the GNU C++ compiler
CFLAGS = -c -Wall :
all: edit
edit: main.o function1.o function2.o
$(cc) main.o function1.o function2.o -o edit
clean:
rm -rf *.o edit
.PHONY: Clean
Declares Clean as a phony target, meaning it’s not a file.
Recommended by LinkedIn
Creating a Modular Makefile
Module Implementation
src/add_sub/add_sub.c
src/add_sub/add_sub.h
src/mul_div/mul_div.c
src/mul_div/mul_div.h
src/main.c
test/test_main.c
Creating Module-Specific Makefiles
src/add_sub/Makefile
src/mul_div/Makefile
Creating the Main Makefile
makefile.rules
makefile.module
makefile.verify
# Summary of common make commands for convenience:
Conclusion
Makefiles are a powerful tool for managing the build process in projects with multiple source files and dependencies. By organizing your project with modular Makefiles, you can streamline and maintain an efficient build system. This tutorial introduced the fundamentals of Makefiles and demonstrated their use in a modular setup. With this foundation, you're ready to start building and managing your own projects using Makefiles.