Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Linux 下從零開始寫一個 makefile

在 Linux 上只要檔案一多,手動下 gcc 指令很快就撐不住。makefile 的價值就是把「哪些檔案改了、要重編誰、怎麼連結」變成可重複執行的規則。以下用一個最經典的加減法範例走完整流程。

第一步:撰寫 add.c

#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;
}

第二步:撰寫 sub.c

#include "test.h"

int sub(int a, int b)
{
    return a - b;
}

第三步:撰寫 test.h

#ifndef _TEST_H
#define _TEST_H

int add(int a, int b);
int sub(int a, int b);

#endif

標頭檔用 include guard 包住,避免同一份宣告被重複引入而產生重定義錯誤,這是 C 語言的基本禮儀。

第四步:理解 makefile 的規則骨架

每一條規則由三個部分組成:

target(目標) : prerequisites(依賴條件)
[TAB]command(執行指令)

最容易被卡住的一點是:command 前面必須是真正的 Tab 字元,用空白鍵打出的對齊在 make 眼中一律無效,只會得到「missing separator」的抱怨。

第五步:寫出可用的 makefile

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 這類工具生成,不必自己維護複雜相依關係。

Copyright © Linux教程網 All Rights Reserved