2011年3月26日 星期六

makefile中的.PHONY(phony target

在makefile中的target中,有一個名為Phony target
但在我的看書上.並沒有針對它的說明

所謂的phony target不是一個真實的file.它只是對一些commands集合的名稱.有二個理由來使用 a.為了避免confilict file name b.改善performance



如果一個rule中的command裡面沒有產生真實的file,則每次的remake它必定會再次被執行其rule

範例:

clean:
        rm *.o temp

因為rm command沒有去建立任何的檔案,因此當你執行rmake clean時,它必定會去執行.

  而對於phony target而言,如果有任何事建立一個名為"clean"的檔案時,它就會停止.
因為其在makefile中的clean沒有任何dependces,所以在執行make clean時,它會去檢查其
時間(因為沒有任何相關的,且其clean已為最新的了.故它不會去執行)
  要解決此一問題時,你可以明確地宣告其target為phony

.PHONY : clean

如此一來.'make clean'就可以不管是否有任何的名為clean的檔案了.
 因為你宣告了它,故make知道它不是真實檔案的名稱.因此宣告phony target是一項好的建議,它不但可增加效能,也能避免存在同一名稱的檔案.

因此,你必須先去宣告其為phony target.如下

.PHONY: clean
clean:
        rm *.o temp

但是,特別注意的是phony target不應該跟real target file相關.假如有時,它的commands會在每次update時make.反之,只是phony target不和real target file相關,則其phony target只會在你特別指定下才會去執行.

phony targets 之間可以有相關的.當一個directory中含有多個program時,最好將所有program之間相依性寫入到一個Makefile中.因為有多個makefile時,你只下make只會找到第一個makefile而已.故你必須將其之間的相依性寫入.

 例:
all : prog1 prog2 prog3
.PHONY : all

prog1 : prog1.o utils.o
        cc -o prog1 prog1.o utils.o

prog2 : prog2.o
        cc -o prog2 prog2.o

prog3 : prog3.o sort.o utils.o
        cc -o prog3 prog3.o sort.o utils.o
如此你就可以來remake all program.或是指定

When one phony target is a dependency of another, it serves as a subroutine of the other. For example, here `make cleanall' will delete the object files, the difference files, and the file `program':


.PHONY: cleanall cleanobj cleandiff

cleanall : cleanobj cleandiff
        rm program

cleanobj :
        rm *.o

cleandiff :
        rm *.diff

沒有留言:

張貼留言