A Complete makefile example
Archive - Originally posted on "The Horse's Mouth" - 2012-03-14 06:56:15 - Graham EllisPart of a series, written to brush up some make notes I'm using for some make training next week
Let's write a complete makefile - from first principles:
# This is our first makefile
# Target "always" never exists, so rules will always run
always:
echo "Hello Make World"
# Rule will only run if "once" already exists
# By touching the file, we create it thus preventing re-runs
once:
echo "single shot"
touch once
# Target "clean" never exists, so this will always run
# extra "@" supresses the echoing of the command being run
# but you still see their output
clean:
@echo "Cleaning up"
@rm once
@echo "Completed"
Let's see that running:
wizard:mc graham$ make -f firstmake
echo "Hello Make World"
Hello Make World
wizard:mc graham$ make -f firstmake
echo "Hello Make World"
Hello Make World
wizard:mc graham$ make -f firstmake once
echo "single shot"
single shot
touch once
wizard:mc graham$ make -f firstmake once
make: `once' is up to date.
wizard:mc graham$
Some things to note:
* If no dependencies are given, the rule is always applied (and if multiple dependencies are given, then the rules are applied if ANY of the files is newer than the target)
* touch is commonly used to create an empty file if you're wanting to perform actions and don't really need an output file at all.
* If you preceed a command with an @symbol, the command is not echoed out as it is run. The first two examples above rather nastily double up the echoed text, but in "clean" that's not the case.
* If an error occurs during the application of a rule, it will cease at that point:
wizard:mc graham$ make clean
Cleaning up
rm: once: No such file or directory
make: *** [clean] Error 1
wizard:mc graham$
but an extra - sign will cause the error to be ignored in that the rule will continue:
@-rm once
* The default makefile is called "makefile" or "Makefile" (both will work). You can use the -f command line option to specify a different file, or the MAKEFILES environment variable though this latter has some implications with regard to nesting of makefiles later on:
wizard:mc graham$ export MAKEFILES=secondmake
wizard:mc graham$ make clean
Cleaning up
wizard:mc graham$