2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

c++のMakefileチュートリアル

Posted at

Makefileとは?

bashコマンド+DSL(独自言語)でc++のビルドが記述されているファイル

基本的な例

まずは、Hello Worldから初めてみよう。
$ touch Makefile
したら以下を記述する。

say_hello:
  echo "Hello World"

スペースの代わりにタブを使わないとエラーになる。

次にmakeコマンドを実行する。
$ make

Hello Worldと表示されれば成功だ。

targetとは?

上の例では、say_helloは関数名のように振舞う。
say_helloのような関数名をtargetと呼び。
echo "Hello World"のように処理本体ををrecipeと呼ぶ。

@echo

@なしのechoを使って、echo "hello"とすると
echo "hello"
"hello"
と二重に表示させる。
これを防ぐためにechoの代わりに、@echoを使う。

実例

次に、generateとcleanターゲットをMakefileに加えよう。


say_hello:
        @echo "Hello World"

generate:
        @echo "Creating empty text files..."
        touch file-{1..10}.txt

clean:
        @echo "Cleaning up..."
        rm *.txt

ターミナルに
$ make
と打つと、先頭のsay_helloのみが実行される。

Makefileは先頭のターゲットをdefault targetと呼ぶ。
generateを実行したい場合
$ make generate
のようにmakeの後ろにtargetを渡す必要がある。

.DEFAULT_GOALを設定する事でdefault targetを変更する事が出来る。

Makefileの先頭に、以下を加えよう。

.DEFAULT_GOAL := generate

makeを実行すると、generateが実行される。
$ make

Creating empty text files...
touch file-{1..10}.txt

複数のターゲットを一度に実行する

targetの後ろに、targetをスペース区切りで渡すことで、複数のtargetをまとめて実行出来る。
ここではallというtarget名だけど、名前はなんでも良い。

all: say_hello generate

say_hello:
        @echo "Hello World"

generate:
        @echo "Creating empty text files..."
        touch file-{1..10}.txt

clean:
        @echo "Cleaning up..."
        rm *.txt

$ make all
Hello World
Creating empty text files...
ファイルが作成される。

say_helloと、generateをまとめて実行出来た。

phony target

makeを実行する前に、特定のphony targetを実行させよう。.PHONYを加える事で、ファイルが既に存在しているかいつファイルが作られたかなどを気にする事なくmakeが実行可能になる。

特定のtargetを実行する。

$ make clean
Cleaning up…
rm *.txt

変数

makefileでは変数を定義出来る。
定義した定数は
${}
で使用する事が出来る。

HELLO = Hello

hello:
  echo ${HELLO}

お分かりのとおり、このレシピは、ターミナルに以下を打ち込むのと一緒だ。
gcc hello.c -o hello

以下のように、変数に値を再代入すると、無限ループが発生してしまう。

CC = gcc
CC = ${CC}

all:
    @echo ${CC}


これを防ぐには、:=オペレーターを使用する。

CC := gcc
CC := ${CC}

all:
    @echo ${CC}

## 実践的なMakefileの例

Usage:

make # compile all binary

make clean # remove ALL binaries and objects

.PHONY = all clean

CC = gcc # compiler to use

LINKERFLAG = -lm

SRCS := foo.c
BINS := foo

all: foo

foo: foo.o
@echo "Checking.."
gcc -lm foo.o -o foo

foo.o: foo.c
@echo "Creating object.."
gcc -c foo.c

clean:
@echo "Cleaning up..."
rm -rvf foo.o foo


## 参考
https://opensource.com/article/18/8/what-how-makefile
2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?