## How to get a Makefile directory path

Posted: 27th September 2015 by Tim in Linux, Make
Tags: , , , , , ,

Sometimes in a Makefile you need to reference something from the directory where the Makefile lives. \$(PWD) won’t work in this instance, since that will return the path from where make was called which may be different if, for example, you use the --directory option. In this case, we can use the following code to find Makefile’s directory:

\$(dir \$(realpath \$(firstword \$(MAKEFILE_LIST))))

Let’s pull this apart and look at each component. For this example, our Makefile path is /tmp/path/to/my/Makefile and contains the following:

include other/Makefile
default:
@echo \$(PWD)
@echo \$(dir \$(realpath \$(firstword \$(MAKEFILE_LIST))))

First, MAKEFILE_LIST will contain all of the Makefiles which have been loaded. If you havent’t included any others, only one will be listed here:
\$(MAKEFILE_LIST) = Makefile other/Makefile

Since we’re only interested in the current Makefile, we strip off the includes:
\$(firstword \$(MAKEFILE_LIST)) = Makefile

Now that we have one file, find the absolute path:
\$(realpath \$(firstword \$(MAKEFILE_LIST))) = /tmp/path/to/my/Makefile

Finally, strip off the file name, leaving only the directory path:
\$(dir \$(realpath \$(firstword \$(MAKEFILE_LIST)))) = /tmp/path/to/my/

So, if we call make --directory=/tmp/path/to/my default from the /tmp directory, the following will be printed:

/tmp
/tmp/path/to/my/

If you’re interested in the path of the last included Makefile, use lastword instead of firstword. For example, you may use lastword from other/Makefile to find that directory.