讀書心得 Managing Projects with GNU Make (1-1) make hello.c

本文出自 Managing Projects with GNU Make 3rd-Robert Mecklenburg(2005)

Chp1. How to Write a Simple Makefile


makefile 的目的在於幫大家處理 source code 的編譯問題,下面是一個簡單的例子


先寫一個 hello.c:

#include <stdio.h>

int main() {
  printf("Hello, World!");
  return 0;
}

在 hello.c 的路徑下新增一個名為 makefile 的文件,內容如下:

<TAB> 是 TAB 鍵的意思,因為 command 要用 "TAB" 開頭

hello: hello.c
<TAB>gcc hello.c -o hello

在終端機輸入 make 指令:

$ make                # 搜尋 makefile 並且 make
gcc hello.c -o hello  # make 會執行 makefile 內的 command

$ ./hello             # 來執行編好的 hello
Hello, World!         # 執行的結果

值得注意的是你也可以用 make hello 明確表示說要 build hello 這個 target,若沒有指定 系統會自動使用 makefile 中的第一個 target 當作 make 的目標。

留言

熱門文章