Chapter 4. Functions
GNU make supports both built-in and user-defined functions. A function invocation looks much like a variable reference, but includes one or more parameters separated by commas. Most built-in functions expand to some value that is then assigned to a variable or passed to a subshell. A user-defined function is stored in a variable or macro and expects one or more parameters to be passed by the caller.
User-Defined Functions
Storing command sequences in variables opens the door to a wide range of applications. For instance, here’s a nice little macro to kill a process:[1]
AWK := awk
KILL := kill
# $(kill-acroread)
define kill-acroread
@ ps -W | \
$(AWK) 'BEGIN { FIELDWIDTHS = "9 47 100" } \
/AcroRd32/ { \
print "Killing " $$3; \
system( "$(KILL) -f " $$1 ) \
}'
endef(This macro was written
explicitly to use the Cygwin tools,[2] so the program name we search for and the options to ps and kill are not standard Unix.) To
kill a process we pipe the output of ps to awk. The awk script looks
for the Acrobat Reader by its Windows program name and kills the process if it is running.
We use the FIELDWIDTHS feature to treat the program
name and all its arguments as a single field. This correctly prints the complete program
name and arguments even when it contains embedded blanks. Field references in awk are written as $1,
$2, etc. These would be treated as make variables if we did not quote them in some way. We can
tell make to pass the $
n reference to awk instead of expanding ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access