Skip to content
Click the above “Linux Community” to subscribe!
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).
Target1: Dependencies Then press Enter + Tab key
Target2: Dependencies Then press Enter + Tab key
Targetn: Dependencies Then press Enter + Tab key
Note: Commands must start with a Tab key.
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:
Using Makefile variables: use them as needed, no type definition required (to reference variables, use $(obj) to include more .o files)
Then the above Makefile program is upgraded as follows:
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:
%.o: %.c # Comment: Pattern matching, automatically compiles .c files to .o files
gcc -o $@ -c $^ # Comment: Wildcard
exe= main # Comment: Name of the final compiled result
obj:= main.o a.o b.o c.o # Comment: Dependency files
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