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

本文出自 Managing Projects with GNU Make 3rd-Robert Mecklenburg(2005)

Chp2. Rules


通常我們會把 source code, makefile 和 header 分開例如:


錯誤的 makefile:

count_words: count_words.o counter.o lexer.o -lfl
        gcc $^ -o $@
count_words.o: count_words.c include/counter.h
        gcc -c $<
counter.o: counter.c include/counter.h include/lexer.h
        gcc -c $<
lexer.o: lexer.c include/lexer.h
        gcc -c $<
lexer.c: lexer.l
        flex -t $< > $@
$ make
make: *** No rule to make target `count_words.c',
needed by `count_words.o'.  Stop.

因為 make 的時候找不到 count_words.c 所以出問題了


在 makefile 中加入 "VPATH = src" 讓它去搜索 src

VPATH 定義了要被搜尋的路徑

VPATH = src

VPATH 可以是多個路徑,在 linux 要用空白或逗號分隔,在 windows 下要用空白或分號分隔

$ make
gcc -c src/count_words.c -o count_words.o
src/count_words.c:2:21: counter.h: No such file or directory
make: *** [count_words.o] Error 1

書裡設定 src/count_words.c 包含 #include <counter.h> 然後 include 的時候會失敗

!!這邊要注意!!使用自動變數才會變成 src/count_words.c


在 makefile 中加入 "CPPFLAGS = -I include"

CPPFLAGS = -I include
$ make
gcc -I include -c src/count_words.c -o count_words.o
gcc -I include -c src/counter.c -o counter.o
flex -t src/lexer.l > lexer.c
gcc -I include -c lexer.c -o lexer.o
gcc count_words.o counter.o lexer.o /lib/libfl.a -o count_words

這樣看起來好像 ok 了,但有一個問題要注意。假設你的 VPATH 有很多路徑而這些路徑下又剛好有著同名的檔案,當你編譯這些同名的檔案時 make 會直接編譯第一個發現的檔案


最後來看看 vpath:

我們把 VPATH 和 CPPFLAGS 用 vpath 來代替

vpath %.c src
vpath %.h include

是不是簡單多了呢

留言

熱門文章