Makefile shell subst $(1)

时间:2023-03-09 10:00:08
Makefile shell subst $(1)

MAKE_3_80_realpath    = $(shell $(top_srcdir)/scripts/realpath.sh '$(subst $(SQUOTE),\\$(SQUOTE),$(1))')

以上Makefile思考好几天不得要领:

今天想通了,是为记。

include $(top_srcdir)/include/mk/functions.mk

functions.mk的内容如下:

SQUOTE            := '

# ' # to keep colorized editors from going nuts

MAKE_3_80_realpath    = $(shell $(top_srcdir)/scripts/realpath.sh '$(subst $(SQUOTE),\\$(SQUOTE),$(1))')

MAKE_3_80_abspath    = $(shell $(top_srcdir)/scripts/abspath.sh '$(subst $(SQUOTE),\\$(SQUOTE),$(1))')

几个要点:

1.'不能单独出现,所以巧妙匹配# '

2.$(1)百思不得其解,后来在source insight中搜索对MAKE_3_80_realpath 的引用 发现:

abs_top_builddir        := $(call MAKE_3_80_abspath,$(top_builddir))

$(1)是call函数中的参数

'$(subst $(SQUOTE),\\$(SQUOTE),$(1))'先对参数进行字符替换,里面有个小trick,‘替换为\'

\\第一个为转移字符

$(top_srcdir)/scripts/realpath.sh
############## realpath.sh ############
. "${0%/*}/lib/file_functions.sh"

######### file_functions.sh ###########
_abspath() {
    echo "$@" | awk -v PWD=$(pwd) '{
    sub(/^[[:space:]]+/, ""); sub(/[[:space:]]+$/, ""); # 1.
    if ($0 == "") {
        print PWD
    } else {
        if (!($0 ~ /^\//)) { # i.
            $0 = PWD "/" $0
        }
        while (gsub(/\/\//, "/")) { }; # ii.
        while (sub(/\/[^\/]+\/\.\.\/?/, "/")) { }; # iii.
        while (sub(/\/\.\//, "/")) { }; # iv.
        sub(/(\/\.)?\/$/, "");
        sub(/^\.\//, "/");
        sub(/\/\.$/, "");
        if ($0 == "") {
            print "/"
        } else {
            if ($0 == ".") {
                print PWD
            } else {
                print
            }
        }
    }
}'
}

_realpath() {
    readlink -f "$@"
}
######### end of file_functions.sh ####
while [ $# -gt 0 ] ; do
    echo -n $(_realpath "$1")
    [ $# -gt 1 ] && echo -n " "
    shift
done
######### end of realpath.sh ##########

MAKE_3_80_realpath    = $(shell $(top_srcdir)/scripts/realpath.sh '$(subst $(SQUOTE),\\$(SQUOTE),$(1))')

MAKE_3_80_abspath    = $(shell $(top_srcdir)/scripts/abspath.sh '$(subst $(SQUOTE),\\$(SQUOTE),$(1))')

_abspath 不想去细究了,直接试一下

ttt -> safe_rm.sh

./abspath.sh ttt

/home/zhangyi/work/ltp-ddt-fmsh-psoc-test/scripts/ttt

./realpath.sh ttt
/home/zhangyi/work/ltp-ddt-fmsh-psoc-test/scripts/safe_rm.sh