make : rule call rule

Makefile

Makefile Problem Overview


In a makefile, can I call a rule from another rule?

Similar to:

rule1:
        echo "bye"
rule2:
        date
rule3:
        @echo "hello"
        rule1

Makefile Solutions


Solution 1 - Makefile

Either use dependencies or recursive making to connect from one rule to another.

Dependencies would be done like this (though the order will be different):

rule1:
        echo "bye"
rule2:
        date
rule3: rule1
        @echo "hello"

Recursive make would be done like this (though it does involve a subprocess):

rule1:
        echo "bye"
rule2:
        date
rule3:
        @echo "hello"
        $(MAKE) rule1

Neither is perfect; indeed, with recursive make you can get into significant problems if you build a loop. You also probably ought to add a .PHONY rule so as to mark those rules above as synthetic, so that a stray rule1 (etc.) in the directory won't cause confusion.

Solution 2 - Makefile

Just add a new rule with the ordering you want..

rule1:
        echo "bye"
rule2:
        date
rule3:
        @echo "hello"

rule4: rule3 rule1

Solution 3 - Makefile

Makefiles are not procedural; "rules" are not like functions. That said, you can specify that one rule is a prerequisite of another:

rule1:
    @echo "Rule 1"

rule2: rule1
    @echo "Rule 2"

If you do make rule2, you should see:

Rule 1
Rule 2

Solution 4 - Makefile

There are two advanced functions in GNU Make which can do this, although it should only be used in extenuating circumstances. This SO is top rated in google.

Rule prerequisites are more recommended, but sometimes you need a post-requisite.

GNU Make Call function

GNU Make Eval function

Essentially, Eval lets you build targets on the fly, and Call allows function like "defines" to be created.

Solution 5 - Makefile

A simple way to do it is:

ifeq (a, b)
	build_target:=one
else
	build_target:=two
endif

mytarget: $(build_target)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJuanPabloView Question on Stackoverflow
Solution 1 - MakefileDonal FellowsView Answer on Stackoverflow
Solution 2 - MakefileJohn EikenberryView Answer on Stackoverflow
Solution 3 - MakefileOliver CharlesworthView Answer on Stackoverflow
Solution 4 - MakefileKevinView Answer on Stackoverflow
Solution 5 - Makefileuser2071070View Answer on Stackoverflow