讀書心得 跟我一起寫 makefile (5-1) makefile 規則總整理

本文出自 跟我一起寫 makefile-陳皓(2005)

Chp5. 書寫規則


這章節主要是將前面的東西做個整理,6 和 7 是之前沒提過的部份


1. 列舉一個規則:

我們會定義一個 "規則",然後 make 會檢查這個規則並決定是否執行相對應指令

foo.o : foo.c defs.h  
    gcc -c foo.c  

如果 foo.c 和 defs.h 的文件日期要比 foo.o 文件日期要新,或是 foo.o 不存在,那下面的指令就會被觸發。 (註: foo.c include defs.h)


2. 規則的语法

target1 target2...: prerequisite1 prerequisite2...  
    command1  
    command2
    ...

targets 和 prerequisites 都是用空格做區隔
command 用 <TAB>開頭
單行太長的話可以使用換行符號 "\"


3. 使用通配符

command 其實就是 shell command 所以能夠使用通配符

clean:  
    rm -f *.o  

4. 指定文件搜尋的路徑

使用 VPATH 或 vpath 可以指定文件的搜尋路徑,有興趣的人可以參考底下這篇:

讀書心得 Managing Projects with GNU Make (2-3) VPATH 和 vpath

5. 偽目標

target 本身不是檔案(例如: clean)。為了避免與系統中同名的檔案發生 up to date error 必須明確地告訴 make 說這不是指同名的檔案

有興趣的話可以參考這篇:

讀書心得 Managing Projects with GNU Make (2-1) Phony Target

6. 多目標

書裡舉的例子是下面這個:
bigoutput littleoutput : text.g  
generate text.g -$(subst output,,$@) > $@  
上述的例子等易於下面的例子:
bigoutput : text.g  
generate text.g -big > bigoutput  
littleoutput : text.g  
generate text.g -little > littleoutput  

$@ 代表 targets 的名稱,其中 target 會輪流被取出,有興趣的話可以參考這篇:

讀書心得 Managing Projects with GNU Make (2-2) Automatic Variables

7. 靜態模式

靜態模式是告訴 make 利用 targets 的名稱去做延伸定義

靜態模式的規則如下:

targets: target-pattern: prereq-patterns  
    commands

這樣有點難以理解,來看個例子吧

objects = foo.o bar.o  
  
all: $(objects)  
  
$(objects): %.o: %.c  
    $(CC) -c $(CFLAGS) $< -o $@  

第一次延伸 target-pattern = %.o,意思是我們的 targets 都是以 ".o" 结尾去形成一個集合

第二次延伸 prereq-pattern = %.c,意思是取 target-parrtern 模式中的 "%"(也就是去掉了".o"),使用 ".c" 结尾形成的新集合

書上還有舉一個例子,當你過濾出所有的 .o 檔案名稱後利用其檔名稱再進行延伸

files = foo.elc bar.o lose.o  
  
$(filter %.o,$(files)): %.o: %.c  
    $(CC) -c $(CFLAGS) $< -o $@  
    $(filter %.elc,$(files)): %.elc: %.el  
    emacs -f batch-byte-compile $<  

留言

熱門文章