MakefileによるC++複数ファイルのコンパイル

1278 ワード

1.次のc++ファイルをいくつか仮定します.
wherewhen.h  wherewhen.c
countdown.h countdown.cはmathを含む.h、ライブラリファイルを接続する必要がある
main.c主関数、main.cは2つのヘッダファイルを含むh and countdown.h
第1のコンパイル方法

g++ -Wall -g wherewhen.c countdown.c main.c -lm -o myprogram

実行可能ファイルmyprogramの生成
第2のコンパイル方法は、それぞれのファイルをコンパイルし、

g++ -Wall -g -c wherewhen.c
g++ -Wall -g -c countdown.c
g++ -Wall -g -c main.c
g++ -g wherewhen.o countdown.o main.o -lm -o myprogram

もし私が変わったらc,次の2ステップのコンパイルを行うだけです

g++ -Wall -g -c wherewhen.c
g++ -g wherewhen.o countdown.o main.o -lm -o myprogram

2.Makefileを採用
上のように3つのファイルがありますh,Student.cpp and main.cpp, main.cppはヘッダファイルStudentを含む.h

CC = g++
CFLAGS = -Wall -g
LDFLAGS = -lm

all: clean Student.o main.o myprogram

Student.o : Student.h
	${CC} ${CFLAGS} -c Student.cpp

main.o : Student.h
	${CC} ${CFLAGS} -c main.cpp

myprogram : Student.o main.o
	${CC} ${CFLAGS} Student.o main.o ${LDFLAGS} -o myprogram
clean:
	rm -rf *.o
	rm -rf myprogram
	

then run make