The gist: put this at the top of the Makefile:
MAKEFILE_PATH := $(realpath $(lastword $(MAKEFILE_LIST)))
MAKEFILE_DIR := $(dir $(MAKEFILE_PATH))MAKEFILE_LIST, according to this,
Contains the name of each makefile that is parsed by make, in the order in which it was parsed. The name is appended just before make begins to parse the makefile. Thus, if the first thing a makefile does is examine the last word in this variable, it will be the name of the current makefile. Once the current makefile has used include, however, the last word will be the just-included makefile.
Which is why we need to put that snippet at the top of the Makefile.
lastword simply gets the last Makefile in the MAKEFILE_LIST. The one we
want. realpath obtains not just the absolute path, but also resolves all the
symlinks along the way. If you don't want symlinks to be resolved, use abspath
in the place of realpath.