This is a bare basics introduction to the Makefile.

The Makefile is a plain text file in the project directory named Makefile with no extension.

There are three key concepts in a Makefile:

  1. dependencies
  2. rules
  3. targets

Suppose we want to create a pdf doc.tex that contains some text and a scatterplot. To do this, we create a data set data.csv. We then write an R script plot-data.R that loads data.csv and creates the scatterplot scatterplot.pdf. We write a LaTeX file doc.tex that combines scatterplot.pdf and text and, when compiled, produces doc.pdf.

In this case, we have the following dependencies:

The Makefile allows us to explicitly define these dependencies.

The Makefile also allows us to provide rules to create targets. In the case of the target scatterplot.pdf, we would use the rule Rscript plot-data.R, which just runs the R script plot-data.R (as you would in the terminal).

The Makefile has the following structure:

target: dependency1 dependency2 etc
  rule1
  rule2
  etc

Importantly, a tab (not spaces!) must precede each rule.

For our example, we would have

scatterplot.pdf: plot-data.R data.csv
  Rscript plot-data.R

This says: > The file scatterplot.pdf depends on plot-data.R and data.csv. To create scatterplot.pdf, run Rscript plot-data.R.

We can add our second target to the Makefile as well:

scatterplot.pdf: plot-data.R data.csv
  Rscript plot-data.R

doc.pdf: doc.tex scatterplot.pdf
  pdflatex doc

Here, pdflatex doc is the command we would run to compile the .tex file into a pdf.

We can use # to include comments:

# compile pdf
doc.pdf: doc.tex scatterplot.pdf
  pdflatex doc

# create scatterplot
scatterplot.pdf: plot-data.R data.csv
  Rscript plot-data.R

We can use the Makefile to create doc.pdf by using the command make doc.pdf or make scatterplot.pdf in the terminal at the project directory (i.e., the same directory as the Makefile). The software knows the dependencies and how to create each file, so it runs everything needed to update the target. For example, if you update plot-data.R and run make doc.pdf, the software realizes that doc.pdf depends on scatterplot.pdf, which depends on plot-data.R. It will update scatterplot.pdf first and then update doc.pdf. If you only update doc.tex and run make doc.pdf, then the software will only update doc.pdf.

Importantly, if you only run make (without supplying the name of the file to make), then the software makes the first target. In this case, itโ€™s doc.pdf, so that make doc.pdf and just make are equivalent.


Creative Commons License
Carlisle Rainey