GNU Make - Unconditionally run a target before any other targets

When writing a (GNU) Makefile, there are times when you need a particular target(s) to be run before anything else.  That can be for example to check the environment, ensure variables are set or prepare a particular directory layout. 


TLDR;

Define a non-phony target for a non-existing file and then include the target as if you were including a real makefile.

For example:
always-run-before-all :
	...

include always-run-before-all

Usecase

Ever since I've started using bmakelib to enhance my makefiles, I've always found myself writing a target ensure-variables, which I then would declare as the prerequisite of almost all other targets.

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 quite repititive and error prone and very not DRY. The better approach is to take advantage of GNU Make's mechanism of includeing and makeing makefiles which is described in details in the manual: The alternative approach which is cleaner and more in line with the declarative nature of a Makefile is
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 : 
	...

This causes ensure-variables and prepare-environment to be executed before anything else is to.
Notice how prepare-environment has a dependency to clean!

Hack yourself a makefile and enjoy this on your own 😄

Comments

Popular posts from this blog

Variables in GNU Make: Simple and Recursive

Checkmate on Your Terms: A Personal Journey with Correspondence Chess

Firefox profiles: Quickly replicate your settings to any machine