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

.SECONDEXPANSION:

all: $(OUT)/foo.o

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

%/.f: mkdir -p $(dir $@) touch $@

.PRECIOUS: %/.f

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.

Conclusion

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.

Pages

About the author

John Graham-Cumming

John Graham-Cumming is Co-Founder at Electric Cloud, Inc . Prior to joining Electric Cloud, John was a Venture Consultant with Accel Partners, VP of Internet Technology at Interwoven, Inc. (IWOV), VP of Engineering at Scriptics Corporation (acquired by Interwoven), and Chief Architect at Optimal Networks, Inc. John holds BA and MA degrees in Mathematics and Computation and a Doctorate in Computer Security from Oxford University. John is the creator of the highly acclaimed open source POPFile project. He also holds two patents in network analysis and has others pending.