Makefile by Example: Functions
Make provides functions for text processing and file manipulation. This sample demonstrates `shell`, `subst`, `foreach`, and `if`.
Code
# shell: Execute a shell command and return output
CURRENT_DIR := $(shell pwd)
DATE := $(shell date +%Y-%m-%d)
# subst: String substitution
# $(subst from,to,text)
PATH_FIX := $(subst /,,$(CURRENT_DIR))
# foreach: Loop over a list
# $(foreach var,list,text)
DIRS := src include lib
MKDIRS := $(foreach dir,$(DIRS),mkdir -p $(dir);)
# if: Conditional expansion
# $(if condition,then-part[,else-part])
CHECK := $(if $(wildcard config.h),ConfigFound,ConfigMissing)
all:
@echo "Building in $(CURRENT_DIR) on $(DATE)"
@echo "Status: $(CHECK)"
$(MKDIRS)Explanation
Make has a rich set of functions for transforming text. Functions are called using the syntax $(function arguments). One of the most powerful is the shell function, which allows you to run an external command and capture its output into a variable. This is useful for getting the current date, git commit hash, or system configuration.
Text processing functions like subst (replace string), patsubst (replace pattern), strip (remove whitespace), and findstring allow you to manipulate filenames and paths. The foreach function allows you to iterate over a list of words and perform an operation on each, which is useful for generating repetitive commands.
The if function provides conditional expansion. It checks if the first argument is non-empty. If it is, it evaluates and returns the second argument; otherwise, it returns the third argument (if provided). This allows for dynamic variable construction based on the state of the system.
Code Breakdown
$(shell pwd) runs the pwd command. The result is assigned to CURRENT_DIR.$(foreach ...) constructs a string of commands: mkdir -p src; mkdir -p include; ...
