vijayst
vijayst

Reputation: 21846

Reordering commands in a Makefile

I have the following makefile

.PHONY: target1
target1: target2
  command1

My job is to run command1 before target2. For that, I have split command1 into command1 and command2 and rewritten the Makefile as follows:

.PHONY: target1
target1:
    command1
target1: target2
    command2

But when I run this Makefile, it is only executing target2 and command2. command1 is not run.

Upvotes: 0

Views: 33

Answers (2)

Renaud Pacalet
Renaud Pacalet

Reputation: 29222

If command1 is the first step to build target2, simply add it in its recipe:

target1: target2
    command2

target2:
    command1
    <rest of target2 recipe>

If you want to execute command1 before building target2, what's missing in your problem statement is a third target which recipe is command1. If command1 creates a file target3 then it is easy:

target1: target2
    command2

target2: target3
    <target2 recipe>

target3:
    command1

If command1 does not create any file, you can use an empty marker file as an indicator that command1 has been executed:

target1: target2
    command2

target2: target3
    <target2 recipe>

target3:
    command1
    touch "$@"

Finally, if target1 and target2 shall be built each time you invoke make, just declare all these as phony:

.PHONY: target1 target2 target3

target1: target2
    command2

target2: target3
    <target2 recipe>

target3:
    command1

Upvotes: 1

Cl&#233;ment Jean
Cl&#233;ment Jean

Reputation: 1916

A simple solution would be to rename the first target1 to something else and call it before the target2 rule. Something like:

.PHONY: target1 target1_cmd
target1_cmd:
    command1
target1: target1_cmd target2
    command2

This will run command1, whatever is in target2 and then run the command2.

I'm not sure I get everything that you are trying to do but let me know if you need more details and explanation.

Upvotes: 1

Related Questions