Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make GNU make to rebuild phony target only when prerequisite changes?

In my case I have requirements target, which installs needed Python packages and test, which runs tests and depends on previous one.

Installing dependencies is a long operation and I want it to be executed only when requirements.txt changes. How can I achieve that?

Here is a simplified example of Makefile, that I have now:

.PHONY: test requirements

requirements: requirements.txt
    pip install -r $<

test: tests/ | requirements
    py.test $^
like image 438
Gill Bates Avatar asked Nov 08 '15 17:11

Gill Bates


People also ask

What are makefile prerequisites?

The prerequisites or dependents are those files that must exist before the target can be successfully created. And the commands are those shell commands that will create the target from the prerequisites. Here is a rule for compiling a C file, foo.c, into an object file, foo.o: foo.o: foo.c foo.h gcc -c foo.c.

What kind of targets should have a phony directive in the makefile?

Some common make targets that are often phony are: all , install , clean , distclean , TAGS , info , check .

What is $@ in makefile?

The file name of the target of the rule. If the target is an archive member, then ' $@ ' is the name of the archive file. In a pattern rule that has multiple targets (see Introduction to Pattern Rules), ' $@ ' is the name of whichever target caused the rule's recipe to be run.

What is the purpose of .phony in a makefile?

Inside the Makefile of a project you can find a . PHONY element followed by a label and then the same label used as a target for the Makefile. . PHONY is actually itself a target for the make commandand and it denotes labels that do not represent files of the project.


1 Answers

As @user1034749 pointed out, Make compares the modification times of files. If you want it to know when requirements.txt has been modified since the last installation, you must give it a file whose modification time is the same as the time of the last installation, so that it can compare the two. In other words, you must have a dummy file and modify it whenever you perform the installation. You can call it anything you like, but I will call it "installation":

.PHONY: test

installation: requirements.txt
    pip install -r $<
    touch $@

test: tests/ | installation
    py.test $^
like image 199
Beta Avatar answered Sep 28 '22 20:09

Beta