2015-06-28

Makefile: Here document

Makefile にターゲットを色々詰め込んでいくと、ターゲットの一覧をヘルプで表示させたくなる。そのようなターゲット「help」を作るのは簡単だが、毎行 echo するとか毎行末 \ エスケープするとか面倒なことはやりたくない。そうなると、じゃあヒアドキュメントはできないの?ってなるが、Makefile 文法とヒアドキュメント文法の相性が悪すぎて正攻法ではどうにもならない。というか私には無理だった。

環境変数を使え、と。なるほど、make に文字列を展開させるのではなく、シェルに実行時展開させれば良いのか。そうすれば make による文法解析を回避できる。

Makefile:

export _help_msg
override define _help_msg
Targets:
  compile    Compile and build sources.
  install    Install into the PREFIX.
  uninstall  Uninstall the installed files.
  clean      Remove all generated files.
  help       This message.
Variables:
  PREFIX     The path to be installed.
endef

help:
	@echo "$$_help_msg"

compile:
install:
uninstall:
clean:
# make help
Targets:
  compile    Compile and build sources.
  install    Install into the PREFIX.
  uninstall  Uninstall the installed files.
  clean      Remove all generated files.
  help       This message.
Variables:
  PREFIX     The path to be installed.

ただし、この方法は環境変数を export するので子プロセスに影響を与える可能性が残るのが少し気持ち悪い。あとエディターによっては(Emacs とか)、行中に半端なクォート(「'」「"」)があると色付けが破綻する。まあ毎行 echo するよりはマシ、ということで妥協するしかないか。