Makefile in Linux: Usage Explained
In Linux, a Makefile is a file that contains a series of targets and dependencies, used to instruct the make command on how to compile and build code. Typically, a Makefile includes the following:
- Define variables: it is possible to define some variables to store parameters needed during the compilation process, such as compiler name and compiler options.
- Definition rule: A rule consists of a target, a colon, and one or more dependencies. The target is the generated file, and the dependencies are the files or other targets needed to generate the target. The rule instructs the make command on how to generate the target file.
- Directive: Following the rules, one or more commands can be executed for the build process. These commands are typically compiler commands or copy commands.
Example Makefile:
CC = gcc
CFLAGS = -Wall
all: program
program: main.o func.o
$(CC) $(CFLAGS) -o program main.o func.o
main.o: main.c
$(CC) $(CFLAGS) -c main.c
func.o: func.c
$(CC) $(CFLAGS) -c func.c
clean:
rm -f *.o program
The example Makefile above defines variables CC and CFLAGS, followed by three rules: all, program, and clean. The all rule sets the target as program, dependent on main.o and func.o, with the command to compile and link these two target files to generate the executable file program. The clean rule is used to remove the generated target files and executable file.
To build a project using a Makefile, simply run the make command in the project directory. The make command will compile and build the code based on the rules and dependencies specified in the Makefile.