【C++ Makefile #2】新增自己的變數

前言

今天我們要來繼續討論 Makefile,
我們來學習如何定義自己的變數。

我們的今天的 Makefile

RM=rm
T=touch

otherfiles = myfile myotherfile
buildfiles = myfile2

all: $(buildfiles)

myfile:
    $(T) myfile

myotherfile:
    $(T) myotherfile

myfile2: $(otherfiles)
    cat myfile myotherfile > myfile2

clean:
    $(RM) $(buildfiles)
    $(RM) $(otherfiles)

說明 - 變數

在這份檔案中,我們定義了四個變數,
其中有兩個是命令相關,另外兩個是檔案相關。

命令相關的變數

  • RM=rm
  • T=touch

檔案相關的變數

  • otherfiles = myfile myotherfile
  • buildfiles = myfile2

說明 - 目標方法 (target)

我們在這份檔案一共定義了五種目標

  • all: 1. 完成「所有 buildfiles」
  • myfile: 1. touch myfile
  • myotherfile: 1. touch 「所有 myotherfile」
  • myfile2: 1. 前提要先完成 「所有 otherfiles」 2. 做 cat myfile myotherfile > myfile2
  • clean: 清除所有檔案

我們這邊特別留意 myfile2 的寫法

myfile2: $(otherfiles)
    cat myfile myotherfile > myfile2

「:(冒號)」後面只要加上 $(otherfiles) 或任何的 target,
就表示我們要先完成目標的 target 做為「前置步驟」

所以像這邊的意思就是,先完成 $(otherfiles),再去做 myfile2

Reference