現象:`SUBDIRS:=./test1/test9 ./test1/test6`,Makefile 中:
subdirs:
for dir in $(SUBDIRS); do \
$(MAKE) -C $$dir; \
done
執行報 `Syntax error: end of file unexpected`。
Make 將整行命令傳給 `/bin/sh -c`,**變數 `$(SUBDIRS)` 在 Make 階段展開**,命令變為:
for dir in ./test1/test9 ./test1/test6; do \
make -C $dir; \
done
但 Make 又將 `$dir` 視為 Make 變數 (空值),導致傳給 shell 的實際命令是 `make -C ` 缺參數,語法錯誤。
SUBDIRS := ./test1/test9 ./test1/test6
subdirs:
@for dir in $(SUBDIRS); do \
$(MAKE) -C $$dir; \
done
SUBDIRS := ./test1/test9 ./test1/test6
.PHONY: subdirs $(SUBDIRS)
subdirs: $(SUBDIRS)
$(SUBDIRS):
$(MAKE) -C $@
# 並行構建:make -j4 subdirs
SUBDIRS := $(wildcard */.)
subdirs: $(SUBDIRS)
$(SUBDIRS): ; $(MAKE) -C $@
總結:**Make 變數用 `$(VAR)`,Shell 變數用 `$$VAR`;多目錄遞迴優先用目標依賴而非手寫 for 迴圈。**