With second expansion the prerequisite list of any rule under goes a second expansion (the first expansion happens when the Makefile is read) just before the rule is used. By escaping any $ signs with a second $ it\'s possible to use GNU Make automatic variables in the prerequisite list.
Using a marker file for each directory and second expansion you can create a Makefile that automatically creates directories only when necessary with a simple addition to the prerequisite list of any rule:
OUT = /tmp/out
$(OUT)/%.o: %.c $$(@D)/.f
@$(COMPILE.C) -o $@ $<
mkdir -p $(dir $@)
The pattern rule used to make .o files has a special prerequisite $$(@D)/.f which uses the second expansion feature to obtain the directory in which the target (from $@ using the D modifier) is to be built.
That directory will be built by the %/.f pattern rule that knows how to build a .f file (and the containing directory). Notice that the .f files are marked as precious so that GNU Make will not delete them. Without this line the .f files are considered to be useless intermediate files and would be cleaned up by GNU Make on exit.
That's enough ways to create directories in GNU Make. I\'ll be back in August with a new column about GNU Make and parallelism.