Makefiles are probably one of the most useful tools in my belt. They allow me to create repeatable tasks which I can run with a simple command.
You may ask, why not just run the commands separately, which obviously works, but you need to remember all those commands and the order of which you run them, or write them in a README or similar. Instead, Makefiles offer a simple way to build repeatable commands for a single or series of other commands in a way that you can quickly run when you come to a project. Especially useful when you have new people take over a project, or when you yourself come back to a project a few months or so later.
You use them via the terminal / command line like so:
cd ~/projects/my-project
make do-something-cool
Where do-something-cool
is the command you want to run in the file.
Many people use Makefiles in different ways, I often don't use many of the more complex features Makefiles have and a number of the tutorials start with a steep learning curve using them.
Instead I'll show you a simple example file from a real project I have.
In this example, I have a project where I need to build / minify some javascript and css for performance. I want to run a linter over some files to be sure the sytnax is a-ok, and then I have written some tests for the code and need to be able to run them quickly after i make changes.
Here's an example of this in a Makefile
file.
build:
jsmin js/app.js > js/app.min.js
cssmin < css/app.css > css/app.min.css
test: lint unit-test
lint:
find . -name \*.php | xargs -L1 -P4 php -l
unit-test:
phpunit .
If you copy this code, make sure you use tabs instead of spaces as Makefiles require them.
Let's break down the above.
make build
runs 2 commands, jsmin and cssmin. These are npm modules i have installed globally. They minify my js and css code.make test
runs 2 other commands but these are other make commands. First it runs lint (which could separately be run asmake lint
, this checks the syntax of my php files for the project, usingfind
to find all the php files, piped toxargs
which then allows me to runphp -l
for each file. Then it runs unit-test, again this could be run on it's own asmake unit-test
which runs my phpunit tests. But having a singlemake test
command allows me to run both with ease.
There's plenty more resources out there for learning more about Makefile's, but hopefully this will show how simple and useful they can be.
It's pre installed on Linux & Mac OSX, and on windows you'll need to download something like MinGW to get it installed.
comments powered by Disqus