5

I have a makefile that has multiple targets for outputting data in different formats, e.g. make html, make pdf, make txt etc. and I would like to have pre-build and post-build steps that run when any of these options are used. I have the pre-build step sorted, but not sure how I can get the post-build step working properly.

.PHONY: html pdf txt pre-build post-build

pre-build:
    do-pre-build-stuff

post-build:
    do-post-build-stuff

html: data.dat
    generate-html data.dat

pdf: data.dat
    generate-pdf data.dat

txt: data.dat
    generate-txt data.dat

data.dat: pre-build
    generate-some-data > data.dat

How can I get the post-build step to run after every target?

DanielGibbs
  • 9,910
  • 11
  • 76
  • 121

1 Answers1

10

You have to write a different rule for each one, unfortunately. But you can make it simpler with a static pattern rule:

html pdf txt: %: real-%
        do-post-build-stuff

real-html: data.dat
        generate-html data.dat

real-pdf: data.dat
        generate-pdf data.dat

real-txt: data.dat
        generate-txt data.dat

This creates targets html, pdf, and txt which depend on the real- versions. The real- versions do the actual work, then after they're done the post-build stuff is done as a recipe in the base target (html, pdf, and txt).

That rule is just a shorthand so you don't have to write it all out; the result is identical:

html: real-html
        do-post-build-stuff

pdf: real-pdf
        do-post-build-stuff

txt: real-txt
        do-post-build-stuff
MadScientist
  • 92,819
  • 9
  • 109
  • 136
  • That looks promising, will try in a moment. Could you please explain what's happening on the first line? – DanielGibbs Apr 11 '14 at 16:45
  • I added a pointer to the make docs describing static pattern rules and a bit of info. – MadScientist Apr 11 '14 at 16:57
  • Why can't `do-post-build-stuff` be its own recipe and called after the prerequisites are fulfilled? – jww Nov 12 '18 at 06:38
  • How would it be "called"? Rules are not functions. The recipe of a rule is invoked after all the prerequisites are completed (if the target needs to be updated). Here they want to run `make pdf` and build just the PDF, then also `do-post-build-stuff`. – MadScientist Nov 12 '18 at 14:05