【C++ Makefile #5】Makefile 內建變數 -「$@」, 「$^」, 「$<」, 「$* 」,「$? 」

前言

今天我們要來繼續討論 Makefile,
(這個是 day 3 的延伸討論)
Makefile 裡面常常造成新手閱讀困擾的「$開頭的」這些符號,
「$@」, 「$^」, 「$<」, 「$* 」,「$? 」,
我們今天來一個個分析他們。

讓 Makefile 超級難閱讀的關鍵字元XDDD,為了看懂就學一下吧!

介紹「$@」, 「$^」, 「$<」, 「$* 」,「$? 」

我們一樣先對 makefile 的邏輯有個概念,依照以下的格式:

target: dependency
    - target 是我們要製作的檔案, - dependency 是我們產生目標檔案的前置需求。
  • 「$@」: 取代 target 名稱,因為我們時常會讓 target 等同於要製作出的檔名,我們就會使用「$@」代替
  • 「$^」: 在多參數的時候,「^」取代的是全部的 dependency,也就是所有做為參數的都會被「$^」參考到。
  • 「$<」: 代表的是第一個 dependency
  • 「$* 」: 代表的是第一個 dependency,但不包含副檔名。
  • 「$? 」: 代表比 targets 還新的 dependency。(在 dependencies 中,有更新需要被重新修改的項目)

範例1

all: library.cpp main.cpp

結果

  • 「$@」: all
  • 「$<」: library.cpp
  • 「$^」: library.cpp main.cpp

範例2

all: test1 test2 test3
    @echo "test1 test2 test3"
    @echo "@=$@"
    @echo "^=$^"
    @echo "?=$?"
    @echo "<=$<"
    @echo "*=$*"

test1:
    @echo "test1"
test2:
    @echo "test2"
test3:
    @echo "test3"
clean:
    @echo "clean"

結果

make
test1
test2
test3
test1 test2 test3
@=all
^=test1.cpp test2.cpp test3.cpp
?=test1.cpp test2.cpp test3.cpp
<=test1.cpp
*=

範例3 - 印出變數

  • 「$* 」: 目前看起來最常用到的用法,我自己普遍看到都是拿來印變數。
abc=123

# print variable
print-% : ; @echo $* = $($*)

結果

> make print-abc
abc = 123

Reference