All writingEnglish

Order-only prerequisites in GNU Make

In a GNU Make rule, a prerequisite usually does two jobs. Make updates it before running the target’s recipe. If the prerequisite is newer than the target, Make also reruns the recipe. Sometimes you only need the first job. That’s what an order-only prerequisite is for.

target: normal-prerequisites | order-only-prerequisites

Make updates prerequisites on both sides of the pipe before building target. Only the names to the left participate in the timestamp check for target. The pipe belongs to the Makefile rule and is independent of the shell commands in its recipe.

An output directory for main.o

Suppose I want to compile main.c into build/main.o. The compiler needs the directory to exist so it can write the object file. Adding a sibling file such as build/notes.txt changes the directory’s timestamp, though, and that has no effect on the compiled code. Here’s how I’d write the rule.

build/main.o: main.c | build
	$(CC) $(CPPFLAGS) $(CFLAGS) -c $< -o $@

build:
	mkdir -p $@

Save that as Makefile in an empty directory, keeping the tabs at the start of the recipe lines. On the first run, Make creates build, then invokes the compiler.

echo 'int main(void) { return 0; }' > main.c
make

Now touch each prerequisite in turn. The pauses give the timestamps room to differ.

sleep 1
touch build
make           # build/main.o is up to date
sleep 1
touch main.c
make           # the compiler runs

Remove the pipe and repeat sleep 1, touch build, and make. This time Make recompiles main.c because the directory is a normal prerequisite. That’s the distinction I use when writing a rule. A source file or header can change the object I’m building, so it goes on the left. The directory just needs to be ready when the compiler opens the output file, so it goes on the right.

References