How to get a Makefile’s directory for including other Makefiles

I experience this problem:

I have a file that includes which in the same directory. is included by the top-level Makefile. and 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 does not work if the top-level Makefile is not in the same directory as

For example, in a directory structure like


it is find. But for


The same include in will reports that 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)/

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

include $(SELF_DIR)/

This will not reply on which directory the top-level Makefile stay in anymore.

Eric Ma

Eric is a systems guy. Eric is interested in building high-performance and scalable distributed systems and related technologies. The views or opinions expressed here are solely Eric's own and do not necessarily represent those of any third parties.

Leave a Reply

Your email address will not be published. Required fields are marked *