Makefile (4)

                      Makefile variables

Makefile variables are divided into: user-defined variables, predefined variables, automatic variables, and environment variables.

 

The contents of the Makefile in the previous blog are as follows:

OBJ =world

OBJS = world.o robot.o human.o animal.o

CC = gcc

CFLAGS = -c -o

$ (OBJ): $ (OBJS)

       $ (CC) $ (OBJS) -o $ (OBJ)

animal.o: animal.c

       $(CC)animal.c $(CFLAGS) animal.o

human.o: human.c

       $(CC)human.c $(CFLAGS) human.o

robot.o: robot.c

       $(CC)robot.c $(CFLAGS)robot.o

world.o: world.c

       $(CC)world.c $(CFLAGS) world.o

clean:

       rm $ (OBJ) $ (OBJS)

 

We observed the contents of the Makefile and found that the target file and the dependency file always appear repeatedly, such as:

animal.o: animal.c

       $(CC)animal.c $(CFLAGS) animal.o

animal.c and animal.o

human.o: human.c

       $(CC)human.c $(CFLAGS) human.o

human.o given human.c

……

At this time, the variables in the Makefile introduce automatic variable rules.

Automatic variables can often replace recurring object and dependency files in Makefiles.

Automatic variables in Makefile are:

       $*: target file name without extension

       $+: all dependent files, separated by spaces, in the order in which they appear

       $?: all dependent files with a timestamp later than the target file, separated by spaces

       $@: Represents the target in a rule

       $^: Indicates the file names of all dependencies of the rule. Note that under normal circumstances $^ will only appear once in the makefile

       $<: Indicates the file name of the first dependency of the rule. If auto-derivation, add the first dependency file name for the rule

 

With automatic variables, the Makefile above can continue to be simplified to:

OBJ =world

OBJS = world.o robot.o human.o animal.o

CC = gcc

CFLAGS = -c -o

$ (OBJ): $ (OBJS)

       $ (CC) $ (OBJS) -o $ (OBJ)

animal.o: animal.c

       $(CC)$^ $(CFLAGS) $@

human.o: human.c

       $(CC)$^ $(CFLAGS) $@

robot.o: robot.c

       $(CC)$^ $(CFLAGS) $@

world.o: world.c

       $(CC)$^ $(CFLAGS) $@

clean:

       rm $ (OBJ) $ (OBJS)

 

We observed the contents of the Makefile and found that the following compilation commands are very similar:

animal.o: animal.c

       $(CC)$^ $(CFLAGS) $@

human.o: human.c

       $(CC)$^ $(CFLAGS) $@

robot.o: robot.c

       $(CC)$^ $(CFLAGS) $@

world.o: world.c

       $(CC)$^ $(CFLAGS) $@

 

Is it possible to write these several compilation commands into one compilation command? This requires the use of wildcards in Makefile: %

Using %, Makefilei can be simplified as follows:

 

OBJ =world

OBJS = world.o robot.o human.o animal.o

CC = gcc

CFLAGS = -c -o

$ (OBJ): $ (OBJS)

       $ (CC) $ (OBJS) -o $ (OBJ)

%.o: %.c

       $(CC)$^ $(CFLAGS) $@

clean:

       rm $ (OBJ) $ (OBJS)

 


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325340175&siteId=291194637