Common GNU makefile directory path

前端 未结 5 1088
我在风中等你
我在风中等你 2020-12-01 00:19

I\'m trying to consolidate some build information by using a common makefile. My problem is that I want to use that makefile from different subdirectory levels, which makes

相关标签:
5条回答
  • 2020-12-01 00:27

    This isn't good style because it adds another dependency (i.e. the realpath binary). Depending on your use case, that may be acceptable.

    ROOT_DIR := $(shell dirname $(realpath $(lastword $(MAKEFILE_LIST))))
    

    If you don't have realpath installed:

    $ sudo apt-get install realpath # on debian and derivatives
    

    Edit: Be sure to use := instead of = because the latter causes make to use late-binding and MAKEFILE_LIST may have changed due to later includes.

    0 讨论(0)
  • 2020-12-01 00:36

    Have you tried doing:

    # Makefile.common
    TOP ?= $(shell pwd)
    COMPONENT_DIR := $(TOP)/component
    COMPONENT_INC := $(COMPONENT_DIR)/include
    COMPONENT_LIB := $(COMPONENT_DIR)/libcomponent.a
    
    # other_component/Makefile
    TOP ?= ..
    include ../Makefile.common
    

    Using the ?= construct will keep TOP from being redefined if it is already set. You can set it to the appropriate value based on where you are in the tree when you invoke make. I confess it's been awhile since I've used GNU make so this may not work or may need some tweaks.

    0 讨论(0)
  • 2020-12-01 00:38

    You should be able to use the MAKEFILE_LIST variable, like this:

    # This must be the first line in Makefile.common
    TOP := $(dir $(firstword $(MAKEFILE_LIST)))
    

    From the documentation:

    As make reads various makefiles, including any obtained from the MAKEFILES variable, the command line, the default files, or from include directives, their names will be automatically appended to the MAKEFILE_LIST variable. They are added right before make begins to parse them. This means that 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.

    0 讨论(0)
  • 2020-12-01 00:43

    write the common stuff in common.mk. Then put the common.mk in the default directories that Make looks for when it encounters an include statement. See the manual for common directories Make looks for.

    You could also put the common.mk in custom directory, and then type make -I customdir.

    Inside the Makefile in each subfolder, you do

    include common.mk
    

    That is all. No need to worry about path and moving things around.

    0 讨论(0)
  • 2020-12-01 00:51

    My solution:

    cwd  :=  $(shell readlink -en $(dir $(word $(words $(MAKEFILE_LIST)),$(MAKEFILE_LIST)))) 
    

    This also works for calls like make -f /opt/some/dir/Makefile whenn your in /opt/other/path/subdir.

    0 讨论(0)
提交回复
热议问题