makefile

Makefile for 2 targets with different prerequisites but with single command to generate both


With 2 targets each having a specific prerequisite and a single command to build them we can use this makefile

a.target: a.req
    build_a_and_b

b.target: b.req
    build_a_and_b

But if the 2 targets require to be built the command will be run twice.

I found that in recent make it exists grouped targets that takes into account commands generating multiple targets:

a.target b.target &: a.src b.src
    build_a_and_b

This solves the above issue but introduce a new anomaly: if no target is obsolete but a.src is newer than b.target the command is run when it should not as b.target depends only on b.src. Of course same error exists also when switching a and b roles.

How would it be possible to execute only once the command when a target is older than its own source only?


Solution

  • Unfortunately there's no way to do this with grouped targets. For a grouped target all the prerequisites are combined for both targets, regardless of how you define them.

    If you don't care about parallel builds you can simply define two rules and the first one that runs will update the other one, then make will see that the second one is already updated and won't run the recipe again.

    If you want to have parallel builds then it's not really possible, because the only way make can know to not build both at the same time is if they are linked together and when link them together you get this result. At least, I can't think of a way to avoid it.