Basics

Posted by Beetle B. on Wed 05 June 2019

Rules The format of a rule is:

TARGET ... : PREREQUISITES ...
       RECIPE
       ...
       ...

The prerequisites are files that are required to run the recipe. Presumably if one of these is updated, it knows to rerun the recipe…?

If you have a lot of prerequisites, split the line with \. Now you may want/need to make rules for some/all of the prerequisites.

All recipe lines must begin with a Tab!

By default, make will start with the first target. Variables Creating rules like the following:

edit : main.o kbd.o command.o display.o \
              insert.o search.o files.o utils.o
        cc -o edit main.o kbd.o command.o display.o \
                   insert.o search.o files.o utils.o


main.o : main.c defs.h
        cc -c main.c
kbd.o : kbd.c defs.h command.h
        cc -c kbd.c
command.o : command.c defs.h command.h
        cc -c command.c
display.o : display.c defs.h buffer.h
        cc -c display.c

<etc>

is hard to maintain because there is redundant information. To solve this, use variables.

objects = main.o kbd.o command.o display.o \
          insert.o search.o files.o utils.o
edit : $(objects)
        cc -o edit $(objects)

Implicit Rules

When compiling individual C files, make has an implicit rule. If it sees a .c file, it will run cc -c main.c -o main.o. So a rule for a given C file would be:

main.o : defs.h

A Different Grouping Note that earlier the files were grouped by object files, and many object files shared a prerequisite. You can instead group by prerequisites:

objects = main.o kbd.o command.o display.o \
          insert.o search.o files.o utils.o

edit : $(objects)
        cc -o edit $(objects)

$(objects) : defs.h
kbd.o command.o files.o : command.h
display.o insert.o search.o files.o : buffer.h

This requires that you use implicit rules. Phony Rules and Clean

.PHONY : clean
clean :
        -rm edit $(objects)

You don’t need the PHONY statement. It is there to tell Make that if there is a file called clean.c, it shouldn’t get confused.

Not sure why rm is preceded with a hyphen…

tags : make