into the void

ソフトウェアに関する雑多な調査日記

GNU Make のいろいろ

ターゲットの重複定義

ターゲットを重複して定義すると

  • ターゲットに対するコマンドは後で定義したものでオーバライド(上書き)される
  • 依存関係は先に定義したものに追加される

Makefile

all: test1.o
    echo "1st define"

all: test2.o
    echo "2nd define"

実行結果

$ make
Makefile:5: warning: overriding commands for target `all'
Makefile:2: warning: ignoring old commands for target `all'
cc    -c -o test2.o test2.c
cc    -c -o test1.o test1.c
echo "2nd define"
2nd define

3回以上重複して定義したときの依存関係の順番は下記のようになる。

all: test1.o
	echo "1st define

all: test2.o
	echo "2nd define"

all: test3.o
	echo "3rd define"

all: test4.o
	echo "4th define"

clean:
	rm *.o
$ make all
Makefile:5: warning: overriding commands for target `all'
Makefile:2: warning: ignoring old commands for target `all'
Makefile:8: warning: overriding commands for target `all'
Makefile:5: warning: ignoring old commands for target `all'
Makefile:11: warning: overriding commands for target `all'
Makefile:8: warning: ignoring old commands for target `all'
cc    -c -o test4.o test4.c
cc    -c -o test1.o test1.c
cc    -c -o test2.o test2.c
cc    -c -o test3.o test3.c
echo "4th define"
4th define

変数のexport

  • 定義した変数をexportしておくとmakeの中から呼び出したmakeに変数を引き継がせることができる。

Makefile

BUILD_DIR=./tmp
export BUILD_DIR

all:
	make -C ./subdir1

subdir1/Makefile

all:
	echo "subdir1 target"
	echo $(BUILD_DIR)
$ make -f Makefile
make -C ./subdir1
make[1]: Entering directory `/home/masashi/tmp/subdir1'
echo "subdir1 target"
subdir1 target
echo ./tmp
./tmp
make[1]: Leaving directory `/home/masashi/tmp/subdir1'

他のmakefileをincludeする

  • includeを使うと他のmakefileをその場所に展開できる。
  • includeで指定したファイルはターゲットとして扱われる。なので、もしファイルが存在しないと警告メッセージを出力した後で、それを生成するルールがないかどうかチェックして、ルールがあれば実行した後でもう一回makefileの読み込みをやり直す。
  • "-include"とかくとファイルが存在しなかったときの警告メッセージの出力を抑制できる。