Last updated on 2023-04-24 | Edit this page
- How can I eliminate redundancy in my Makefiles?
- Use variables in a Makefile.
- Explain the benefits of decoupling configuration from computation.
Despite our efforts, our Makefile still has repeated content, i.e.
the name of our script –
countwords.py, and the program we
use to run it –
python. If we renamed our script we’d have
to update our Makefile in multiple places.
This is a variable assignment
COUNT_SRC is assigned the value
We can do the same thing with the interpreter language used to run the script:
$(...) tells Make to replace a variable with its value
when Make is run. This is a variable reference. At any place where we
want to use the value of a variable we have to write it, or reference
it, in this way.
Here we reference the variables
COUNT_SRC. This tells Make to replace the variable
LANGUAGE with its value
python, and to replace
COUNT_SRC with its value
Defining the variable
LANGUAGE in this way avoids
python in our Makefile, and allows us to easily
change how our script is run (e.g. we might want to use a different
version of Python and need to change
python2 – or we might want to rewrite the script using
another language (e.g. switch from Python to R)).
We place variables at the top of a Makefile so they are easy to find
and modify. Alternatively, we can pull them out into a new file that
just holds variable definitions (i.e. delete them from the original
Makefile). Let us create
# Count words script. LANGUAGE=python COUNT_SRC=countwords.py # Test Zipf's rule ZIPF_SRC=testzipf.py
We can then import
We can re-run Make to see that everything still works:
$ make clean $ make dats $ make results.txt
We have separated the configuration of our Makefile from its rules –
the parts that do all the work. If we want to change our script name or
how it is executed we just need to edit our configuration file, not our
source code in
Makefile. Decoupling code from configuration
in this way is good programming practice, as it promotes more modular,
flexible and reusable code.