Making directories in GNU Make


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


all: $(OUT)/foo.o

$(OUT)/%.o: %.c $$(@D)/.f
    @$(COMPILE.C) -o $@ $<

    mkdir -p $(dir $@)
    touch $@


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.

About the author

AgileConnection is one of the growing communities of the TechWell network.

Featuring fresh, insightful stories, is the place to go for what is happening in software development and delivery.  Join the conversation now!