A Simple Introduction to Makefile

Click the above “Linux Community” to subscribe!
1. Introduction
The make command requires a Makefile to tell it how to compile and link the program (simply put: it manages the project files and determines which files to compile first and in what order).
2. Writing Rules:
Target1: Dependencies Then press Enter + Tab key
Command;
Target2: Dependencies Then press Enter + Tab key
Command;
Targetn: Dependencies Then press Enter + Tab key
Command;
Note: Commands must start with a Tab key.
3. Evolution of Makefile
1. A project has five files: main.c/a.c/a.h/b.c/b.h; main.c includes a.h and b.h and uses related functions; then create a new Makefile with the following content:
main: a.o b.o
gcc -o main a.o b.o
a.o: a.c
gcc -c a.c -o a.o
b.o: b.c
gcc -c b.c -o b.o
2. Makefile Upgrade 1
Using Makefile variables: use them as needed, no type definition required (to reference variables, use $(obj) to include more .o files)
Method: obj:= a.o b.o
Then the above Makefile program is upgraded as follows:
obj:= a.o b.o
main: $(obj)
gcc -o main a.o b.o
a.o: a.c
gcc -c a.c -o a.o
b.o: b.c
gcc -c b.c -o b.o
3. Makefile Upgrade 2
After compiling with the above two Makefiles, the project executes successfully. However, if main.c needs to reference functions from more files, do we need to write so many compilation commands? Clearly, this method is not feasible.
Improvement: special variables and automatic inference in Makefile
Explanation of Knowledge Points:
$@ represents the target name,
$^ represents the dependency files
% represents any character
%.o represents any .o file
%.c represents any .c file
The above Makefile is upgraded as follows:
obj:= a.o b.o
main: $(obj)
gcc -o main $(obj)
%.o: %.c # Comment: Pattern matching, automatically compiles .c files to .o files
gcc -o $@ -c $^ # Comment: Wildcard
clean:
rm -rf *.o main
4. Makefile Upgrade 3
exe= main # Comment: Name of the final compiled result
obj:= main.o a.o b.o c.o # Comment: Dependency files
all: $(obj)
gcc -o $(exe) $(obj)
%.o: %.c
gcc -c $^ -o $@
clean:
rm -rf $(obj) $(exe)
The above program seems to have no issues, but the clean command has a flaw. What if there is also a file named clean? If make clean is executed, this command cannot be performed.
This article has a permanent update link: http://www.linuxidc.com/Linux/2017-06/145306.htm
Click
Read the original text
Learn more details

Leave a Comment