Skip to content

Instantly share code, notes, and snippets.

@biplab37
Last active August 4, 2020 07:05
Show Gist options
  • Save biplab37/ad41ad4d9e8c2a805f2a77f3712c3636 to your computer and use it in GitHub Desktop.
Save biplab37/ad41ad4d9e8c2a805f2a77f3712c3636 to your computer and use it in GitHub Desktop.
Makefile

How to create a Makefile

Sometime in a project to run or build it you need to run multiple commands depending on the files that are present. This sometime is cumbersome and typing the same long command again and again is tedious. Having a Makefile can save the day. You can save your code in a makefile and then just type make in the terminal to run it.

Content of the file

Content in the makefile is very simple. The basic structure is

target: dependencies
   command
  • target This is the file that will be changed.
  • dependencies The main file dependes on any of these files. The program will run only if any of these files changes.
  • command Literally the command that you type in terminal

An Example

Let's take an example, Suppose I have a folder with latex files

.
├── image
│   ├── img1.tex
│   └── img2.png
├── main.tex
├── Makefile
├── references.bib
└── subfiles
    ├── subfile1.tex
    └── subfile2.tex

Typically we need to run pdflatex and bibtex and then pdflatex couple of times to resolve the cross-referencing. Usually this process is automated by using latexmk. So here is a simple Makefile which will automatically call latexmk whenever there is a change in any of the file that main.tex depends on.

MAINFILE=main
BIBFILE=$(shell echo "*.bib")
IMAGEFILES=$(shell echo "image/*")
SUBFILES=$(shell echo "subfiles/*")

${MAINFILE}.pdf: ${MAINFILE}.tex $(SUBFILES) $(IMAGEFILES) $(BIBFILES)
    latexmk -pdf -dvi- -pv -silent ${MAINFILE}.tex

.PHONY: clean
clean:
    rm -f *.aux
    rm -f *.toc
    rm -f *.bbl
    rm -f *.blg
    rm -f *.out

where the arguments in latexmk are -pdf use pdflatex and generate pdf -dvi- do not give dvi file as output -pv preview the output file after compilation -silent do not write too many stuff in the terminal

and the clean is another function which cleans out unnecessary files. This program is not automatically called as it doesnot depend on any files. So one has to type the following command to run it

>>> make clean

Also .PHONY is used so that it knows that this function doesnot depend on any file and hence the program should not have to check the files before running it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment