henriquehbr.xyz

Blog Supporters Resume
Part time open-sourcerer, Linux enthusiast, Rust fanatic

Defining custom functions in a Makefile

February 25, 2022

The syntax for defining functions and variables in make is essentially the same, the only difference is that functions accept parameters, that are expressed as numerical variables, each parameter is represented by a number equivalent to the order they were passed, the first parameter is represented by $(1), the second by $(2), and so on, example below:

greet = echo "Hello $(1)!"

The one liner function above simply writes a “Hello” followed by the parameter that was passed to it, so if we wanted to output a "Hello World!", we would call the function above like this:

$(call greet,World)

To better understand how functions (and variables) behave in make, consider them as C macros, which basically does a simple text replacement on the place where it was called, this allows us to use not only shell script, but also the built-in functions provided by make inside our functions for more complex tasks:

parentdir = $(shell basename $(dir $(1)))

The example above receives a file path as a parameter, strips out the filename part with the dir built-in function, and extracts the parent directory name using the basename system tool through the built-in shell function

Functions can also be multi-line, for that, they must be declared with a slightly different syntax (the same applies for variables)

define greet
  echo "Hello $(1)!"
endef

All the previously mentioned concepts also applies to multi-line functions as well

For more in-depth details regarding both the one-liner and the multi-line syntaxes, consider checking the official documentation

Special thanks