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.

>Solution :

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:
    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.

Leave a Reply