GNU Make: Unconditionally Run a Target Before Any Other Target

Define a non-phony target for a file that does not exist, then include that target as if it were a makefile. GNU Make will attempt to update it before processing the requested targets.

When writing a GNU Makefile, there are times when you need a particular target to run before anything else. That can be useful for checking the environment, ensuring variables are set, or preparing a directory layout.

For example:

always-run-before-all :
    ...

include always-run-before-all

The repetitive approach

When using bmakelib to enhance a Makefile, I often found myself writing an ensure-variables target and making it a prerequisite of almost every other target:

include bmakelib/bmakelib.mk

#######################################

.PHONY : ensure-variables

ensure-variables : bmakelib.error-if-blank( REQUIRED_VAR1 REQUIRED_VAR2 )
ensure-variables : bmakelib.default-if-blank( OPTIONAL_VAR,some-value )

########################################

my-target : ensure-variables
    ...

#######################################

another-target : ensure-variables
    ...

#######################################

yet-another-target : ensure-variables
    ...

This is repetitive, error-prone, and far from DRY. GNU Make has a cleaner mechanism: it can remake included makefiles before it runs the requested targets. The manual explains including other makefiles and how makefiles are remade.

Include the setup targets

Instead of adding each setup target as a prerequisite, include its name as a makefile. Keep the target non-phony and ensure that the corresponding file does not exist:

include bmakelib/bmakelib.mk

#######################################

ensure-variables : bmakelib.error-if-blank( REQUIRED_VAR1 REQUIRED_VAR2 )
ensure-variables : bmakelib.default-if-blank( OPTIONAL_VAR,some-value )

include ensure-variables

#######################################

prepare-environment : clean
prepare-environment :
    ...

include prepare-environment

########################################

my-target :
    ...

#######################################

another-target :
    ...

#######################################

yet-another-target :
    ...

#######################################

.PHONY : clean

clean :
    ...

GNU Make tries to remake included makefiles before processing the requested targets. Since these targets do not create files with those names, their recipes run on each invocation; if the included file was not changed, Make continues without restarting. Notice that prepare-environment depends on clean, so the cleanup runs first.

Try it in your own Makefile and enjoy the simpler setup.


Comments