Simple example of Makefile compilation rules

Suppose there is a C language project that contains three files, namely main.c, foo.c and bar.c, and a header file foo.h. Now we want to compile the project using the Makefile.

First, we need to create a file called Makefile, open it with a text editor and edit it. Here is a simple Makefile example:

CC = gcc
CFLAGS = -Wall -g

all: myprog

myprog: main.o foo.o bar.o
	$(CC) $(CFLAGS) -o $@ $^

main.o: main.c foo.h
	$(CC) $(CFLAGS) -c $< -o $@

foo.o: foo.c foo.h
	$(CC) $(CFLAGS) -c $< -o $@

bar.o: bar.c
	$(CC) $(CFLAGS) -c $< -o $@

clean:
	rm -f myprog *.o

The Makefile contains the following rules:

  • CC: Define the compiler as gcc.
  • CFLAGS: Define compilation options, including enabling warning options -Wall and generating debugging information options -g.
  • all: Defines a default rule that depends on myprog.
  • myprog: Define the target as myprog, which depends on the three targets main.o, foo.o and bar.o, and execute the gcc command to link them together to generate the myprog executable file.
  • main.o: Define the target as main.o, which depends on the two files main.c and foo.h. Execute the gcc command to compile main.c into the main.o target file.
  • foo.o: Define the target as foo.o, which depends on the two files foo.c and foo.h. Execute the gcc command to compile foo.c into the foo.o target file.
  • bar.o: Define the target as bar.o, which depends on the bar.c file, and execute the gcc command to compile bar.c into the bar.o target file.
  • clean: Define a cleanup rule, execute the rm command to delete all generated files, including the myprog executable file and three object files.
  • Among them, $@ represents the current target name, and $^ represents all targets that the current target depends on. We can add the -o option to this command to modify the name of the generated executable

Now, we enter the project directory in the terminal and run the make command to automatically compile the entire project. If all goes well, an executable named myprog will eventually be produced.

Note: In Makefile, indentation is very important, it determines the execution order and hierarchical relationship of commands in each rule. Therefore, be sure to use the Tab key for indentation, not spaces.

Guess you like

Origin blog.csdn.net/qq_20173195/article/details/130528889