makefile介紹及示例

2021-09-29 16:27:33 字數 1240 閱讀 4784

乙個開發工程會有很多的原始檔,它們按型別、功能、模組分別放在若干個目錄中,makefile定義了一系列的規則來指定,哪些檔案需要先編譯,哪些檔案需要後編譯,哪些檔案需要重新編譯等。makefile檔案關係到整個工程的編譯規則。寫好的makefile,只要執行make命令,就會按makefile裡定義好的規則來編譯工程。

make 是乙個用來解析makefile檔案中的指令的命令工具。大多數的 ide 都有這個命令,如linux下 gnu 的 make。不同產商的 make各不相同,我們這裡只介紹linux上的make,版本為gnu make 4.1,預設的編譯器是gcc。

可以參考《gcc編譯程式的過程》

target ...

: prerequisites ...

command ..

....

target:可以是目標檔案、執行檔案、標籤。

prerequisites: 生成該 target 所依賴的檔案或 target。

command:生產該 target 要執行的命令(任意的 shell 命令),即生成規則定義在 command 中。

注意:

prerequisites 中如果有乙個以上的檔案比 target 檔案要新的話,command 所定義的命令就會被執行。

依賴關係的實質就是說明目標檔案是由哪些檔案生成的,目標檔案是由哪些檔案更新的。

在定義好依賴關係後,command定義了生成目標檔案的指令,指令前一定要以乙個 tab鍵作為開頭

make命令會比較 targets檔案和 prerequisites 檔案的修改日期。如果 prerequisites 檔案的日期比 targets 檔案的日期新,或者 target 不存在的話,那麼make 就會執行command定義的命令。

main.o:main.c hello.h

gcc -c main.c

hello.o:hello.c hello.h

gcc -c hello.c

clean:

makefile中的指令都要寫在同一行,如果實在要換行,可以在行尾加反斜槓(\ )換行符,如:

main.o:main.c hello.h

gcc -c\

main.c

hello.o:hello.c hello.h

gcc -c hello.c

clean:

謝謝閱讀!

Makefile介紹及Makefile是如何工作的

make命令執行時,需要乙個 makefile 檔案,以告訴make命令如何去編譯和鏈結程式。首先,我們用乙個示例來說明makefile的書寫規則。以便給大家乙個感性認識。這個示例 於gnu的make使用手冊,在這個示例中,我們的工程有8個c檔案,和3個頭檔案,我們要寫乙個makefile來告訴ma...

makefile語法示例

edit main.o kbd.o cc o edit main.o kdb.o main.o main.c defs.h cc c main.c kbd.o kbd.c defs.h command.h cc c kbd.c clean rm o edit makefile中使用變數 object...

Makefile示例學習

裸機程式中的makefile是把程式的編譯和鏈結過程分開的,編譯要使用編譯器gcc,鏈結使用鏈結器ld 示例 led.bin start.o arm linux ld ttext 0x0 o led.elf arm linux objcopy o binary led.elf led.bin arm...