Skip to content

Instantly share code, notes, and snippets.

@nguyenvukhang
Last active January 25, 2026 02:40
Show Gist options
  • Select an option

  • Save nguyenvukhang/2988f25f90c7f98f8a9da573df4f22fb to your computer and use it in GitHub Desktop.

Select an option

Save nguyenvukhang/2988f25f90c7f98f8a9da573df4f22fb to your computer and use it in GitHub Desktop.
Getting the absolute path of the current `Makefile`

The gist: put this at the top of the Makefile:

MAKEFILE_PATH := $(realpath $(lastword $(MAKEFILE_LIST)))
MAKEFILE_DIR := $(dir $(MAKEFILE_PATH))

Explanation

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment