How to get a Makefile’s directory for including other Makefiles
Posted on In QAI experience this problem:
I have a file common.mk that includes release.mk which in the same directory. common.mk is included by the top-level Makefile. common.mk and release.mk are shared by multiple projects and the top-level Makefile may stay in different directories with {common,release}.mk.
Now, include
in make use the pwd
as base directory. So, simply include release.mk
does not work if the top-level Makefile is not in the same directory as releas.mk
.
For example, in a directory structure like
Makefile
common.mk
release.mk
it is find. But for
Makefile
external/common.mk
external/release.mk
The same include release.mk
in commin.mk will reports that release.mk does not exists.
In bash, we can use $(dirname $0)
to get the current script’s directory. How to achieve the similar thing in Makefile so that I can use include $(self_dir)/release.mk
?
The key is to find the “current” makefile’s directory:
SELF_DIR := $(dir $(lastword $(MAKEFILE_LIST)))
SELF_DIR
will contain the directory of the makefile which contains this piece of code. So you can include
the release.mk by:
include $(SELF_DIR)/release.mk
This will not reply on which directory the top-level Makefile stay in anymore.