Created: 2023-08-20 14:03
Status: #concept
Subject: Programming DevOps
Tags: Bash CLI Linux

Makefile

It is a script containing rules to be executed when we run make Makefile.

  • they are typically used to build C projects, but can be used elsewhere as a Build script.

Rule Syntax

TARGET: ...DEPENDENCIES
	COMMANDS_TO_RUN_TO_BUILD_TARGET

For example, let's make a file called Makefile in the Directory that contains all the dependencies.

all: justify

justify: justify.o word.o line.o
	gcc -o justify justify.o word.o line.o

justify.o: justify.c word.h line.h
	gcc -c justify.c

word.o: word.c word.h
	gcc -c word.c 

line.o: line.c line.h 
	gcc -c line.c 

clean:
	rm -f factorial main.o factorial.o
When we run make without any target arguments, it will run the first target rule.

In this case, it is make all.

Running make

make all         # runs all the rules to build justify
make justify.o   # only builds justify.o

Using Variables

We use the IDENTIFIER := VALUE syntax to declare variables.

  • we use them similarly to Bash scripts with $(IDENTIFIER).
  • we can use IDENTIFIER ?= POSSIBLE_ENV_VALUE to conditionally assign a value if it's not an Environment Variable already.

See more ways to assign variables here.

Automatic Variables

There are extra variables that have semantic meaning.

  • $@ is the name of the rule's TARGET.
  • $< is the name of the FIRST dependency.
  • $^ are the names of ALL dependencies.
CC     ?= gcc
CFLAGS := -Wall -Werror

all: program 

program: program.o dependency.o
	$(CC) $(CFLAGS) $^ -o $@ 

program.o: program.c dependency.h
	$(CC) $(CFLAGS) -c $<

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

clean:
	rm program program.o dependency.o

Overriding Defined Variables

We can override defined variables by passing VARIABLE=value after make <rule>.

  • so, to override CC := gcc, we do make all CC=clang.

Read more about overriding here.

TMPDIR := "/tmp"
test:
    @echo $(TMPDIR)
$ make
> /tmp
$ make test
> /tmp
$ make TMPDIR=overridenValue
> overridenValue

References