在 Linux 上只要檔案一多,手動下 gcc 指令很快就撐不住。makefile 的價值就是把「哪些檔案改了、要重編誰、怎麼連結」變成可重複執行的規則。以下用一個最經典的加減法範例走完整流程。
#include "test.h"
#include <stdio.h>
int add(int a, int b)
{
return a + b;
}
int main()
{
printf(" 2 + 3 = %d\n", add(2, 3));
printf(" 5 - 3 = %d\n", sub(5, 3));
return 1;
}
#include "test.h"
int sub(int a, int b)
{
return a - b;
}
#ifndef _TEST_H #define _TEST_H int add(int a, int b); int sub(int a, int b); #endif
標頭檔用 include guard 包住,避免同一份宣告被重複引入而產生重定義錯誤,這是 C 語言的基本禮儀。
每一條規則由三個部分組成:
target(目標) : prerequisites(依賴條件) [TAB]command(執行指令)
最容易被卡住的一點是:command 前面必須是真正的 Tab 字元,用空白鍵打出的對齊在 make 眼中一律無效,只會得到「missing separator」的抱怨。
all: app app: add.o sub.o gcc -o app add.o sub.o add.o: add.c test.h gcc -c add.c sub.o: sub.c test.h gcc -c sub.c clean: rm -f *.o app .PHONY: all clean
在終端機執行 make 就會依序編出目的檔並連結;改了 header 之後,make 會自動把相依的 .o 一起重編,這正是把 test.h 列進依賴的意義。想從乾淨狀態重來,執行 make clean 即可。
把重複的細節抽成變數,makefile 會好維護很多,例如 CC = gcc、CFLAGS = -Wall -O2,再以 $(CC) $(CFLAGS) 引用。若專案規模再大一點,可以改用 %.o: %.c 的型別規則消除重複條目,或直接交給 automake、CMake 這類工具生成,不必自己維護複雜相依關係。