makefiledirectorycompilation

How to get the name the parent directory of the current directory within a Makefile?


Suppose I have Makefile in /myPDir/myCurrDir. Inside a Makefile I can retrieve the name of the current directory as:

CURR_DIR_NAME  := $(notdir $(CURDIR))
$(warning CURR_DIR_NAME IS $(CURR_DIR_NAME))

or

CURR_DIR_NAME  := $(shell basename $(CURDIR))
$(warning CURR_DIR_NAME IS $(CURR_DIR_NAME))

and the second line in both cases will print myCurrDir.

Now I want to obtain the name of the parent directory, i.e. myPDir. I tried to use instead of $(CURDIR), $(CURDIR)/.. but it does not work and prints ....

How can I refer the name of the parent directory, i.e. get the string myCurrDir in the example, as a variable in a Makefile?


Solution

  • Using $(abspath $(<whatever>)/..)

    Commands like notdir or the shell's basedir are simple text string parsers. So if you say basename foo/.. it just returns the .. since that's the last element on the path.

    If you want the parent directory there are various ways to do it. One simple way is to use the make abspath function to convert the relative path to an absolute path: $(abspath /foo/bar/biz/..) will return /foo/bar. So, you can use:

    PARENT = $(notdir $(abspath $(CURDIR)/..))