[Linux] Makefile writing tutorial

The following is an example of writing a simple Linux Makefile for compiling a C language program:

CC = gcc
CFLAGS = -Wall -g
TARGET = myprogram
SRCS = main.c foo.c bar.c
OBJS = $(SRCS:.c=.o)

all: $(TARGET)

$(TARGET): $(OBJS)
	$(CC) $(CFLAGS) -o $@ $^

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

clean:
	rm -f $(OBJS) $(TARGET)

The Makefile contains the following sections:

  1. Define variables:
  • CC: Compiler.
  • CFLAGS: Compilation options, including -Wall (display all warning messages) and -g (generate debug information).
  • TARGET: The name of the target program.
  • SRCS: List of source files.
  • OBJS: List of object files.
  1. Define the rules:
  • all: the default rule, compile the target program.
  • ( TARGET ): target program rule, dependent on target file list (TARGET): target program rule, dependent on target file list( T A RGET ) : target program rules, dependent on object file list (OBJS), use compiler( CC ) and compile options ( CC ) and compile options( CC ) and compilation options (CFLAGS) to generate an object program.
  • (OBJS): Object file rules, dependent on corresponding source files, using compiler (OBJS): Object file rules, dependent on corresponding source files, using compiler( OB J S ) : Object file rules, dependent on the corresponding source files, using the compiler (CC) and compilation options $(CFLAGS) to generate object files.
  • %.o: Wildcard rules, used to generate object files, dependent on corresponding source files, using compiler ( CC ) and compilation options (CC) and compilation options( CC ) and compilation options (CFLAGS) to generate object files.
  • clean: clean up rules, delete target files and target programs.
  1. Execution rules:
  • make: Execute the default rules and compile the target program.
  • make clean: Execute cleanup rules to delete target files and programs.

The Makefile can be modified according to the actual situation, such as adding the path of the header file, the path of the library file, and the library file.

Guess you like

Origin blog.csdn.net/qq_37286579/article/details/130603140