Makefile 簡介
一個(gè)工程中的源文件不計(jì)其數(shù),按其類型、功能、模塊分別放在若干個(gè)目錄中。makefile定義了一系列的規(guī)則來指定,哪些文件需要先編譯,哪些文件需要后編譯,哪些文件需要重新編譯,甚至進(jìn)行更復(fù)雜的功能操作(因?yàn)閙akefile就像一個(gè)shell腳本一樣,可以執(zhí)行操作系統(tǒng)的命令)。
makefile帶來的好處就是——“自動(dòng)化編譯”,一但寫好,只需要一個(gè)make命令,整個(gè)工程完全編譯,極大的提高了軟件的開發(fā)效率。make是一個(gè)命令工具,是一個(gè)及時(shí)makefile中命令的工具程序。
make工具最主要也是最基本的功能就是根據(jù)makefile文件中描述的源程序至今的相互關(guān)系來完成自動(dòng)編譯、維護(hù)多個(gè)源文件工程。而makefile文件需要按某種語法進(jìn)行編寫,文件中需要說明如何編譯各個(gè)源文件并鏈接生成可執(zhí)行文件,要求定義源文件之間的依賴關(guān)系。
Makefile規(guī)則
我們以多個(gè)文件來示例。
// prog.c
#include <stdio.h>
#include "code.h"
int main(void)
{
int i = 1;
printf ("myfun(i) = %d\n", myfun(i));
}
// code.c
#include "code.h"
int myfun(int in)
{
return in + 1;
}
// code.h
extern int myfun(int);
Make的規(guī)則是:
test(目標(biāo)文件): prog.o code.o(依賴文件列表)
tab(一個(gè)tab來隔開) gcc prog.o code.o -o test(命令)
然后我們生成Makefile文件。
test: prog.o code.o
gcc prog.o code.o -o test
prog.o: prog.c code.h
gcc -c prog.c -o prog.o
code.o: code.c code.h
gcc -c code.c -o code.o
clean:
rm -f *.o test
使用make命令執(zhí)行Makefile。
make
gcc prog.o code.o -o test
gcc -c code.c -o code.o
gcc prog.o code.o -o test
./test
//清除.o和test文件
make clean
使用宏
Makefile還可以定義和使用宏(也稱做變量),從而使其更加自動(dòng)化,更加靈活,在Makefile中定義宏的格式為:
macroname = macrotext
使用宏的格式為:
$(macroname)
上面的Makefile改為使用宏
OBJS = prog.o code.o
CC = gcc
test: $(OBJS)
$(CC) $(OBJS) -o test
prog.o: prog.c code.h
$(CC) -c prog.c -o prog.o
code.o: code.c code.h
$(CC) -c code.c -o code.o
clean:
rm -f *.o test