C語言 add、sub、mul 和 div 程式的 Makefile
什麼是 Makefile?
Makefile 是許多程式設計專案中使用的一個獨特檔案,它可以透過編譯和連結自動生成可執行程式。它提供了關於連結和編譯程式的指令,以及原始檔依賴項和構建命令的列表。名為 make 的程式讀取 Makefile 並執行所需的命令。
Makefile 的一般格式
- 指定編譯器(gcc 用於 C 程式設計 和 g++ 用於 C++ 程式設計)。
- 指定編譯器標誌。
- 定義目標可執行檔案。
- 定義預設目標(all)。
- 將原始檔編譯並連結到可執行檔案。(也可以使用目標檔案)。
- 清理目標以刪除可執行檔案。
讓我們看看 C 語言中加法、減法、乘法和除法程式的 Makefile 示例。
add、sub、mul 和 div 程式的 Makefile
# Compiler to use
CC = gcc
# Compiler flags
CFLAGS = -Wall -g
# Target executable names
TARGETS = add sub mul div
# Default target when running "make"
all: $(TARGETS)
run_add:add
@./add
run_sub:sub
@./sub
run_mul:mul
@./mul
run_div:div
@./div
# Rule for creating the addition program
add: add.c
@$(CC) $(CFLAGS) -o add add.c
# Rule for creating the subtraction program
sub: sub.c
@$(CC) $(CFLAGS) -o sub sub.c
# Rule for creating the multiplication program
mul: mul.c
@$(CC) $(CFLAGS) -o mul mul.c
# Rule for creating the division program
div: div.c
@$(CC) $(CFLAGS) -o div div.c
# Clean up object files and executables
clean:
rm -f $(TARGETS)
Makefile 執行說明
- CC = gcc:此行將gcc 設定為用於編譯 C 程式的編譯器。
- CFLAGS = -Wall -g:在這裡,-Wall 啟用所有警告,這有助於識別程式碼中潛在的問題。-g 使用 gdb 等工具生成除錯資訊。
- 這裡, TARGETS 是一個包含可執行檔名稱的變數。稍後我們可以使用$(TARGETS) 來引用所有目標,而不是重複鍵入每個名稱。
- all: 這是在不帶任何特定指令呼叫 make 時執行的預設目標。
- add: add.c: 它定義了將add.c 編譯成可執行檔案add 的規則
@$(CC) $(CFLAGS) -o add add.c 執行編譯器命令,使用gcc 和指定的標誌(-Wall -g)建立 add 可執行檔案。其他操作與此類似。 - run_<operation> 允許編譯和執行每個程式 run_add 編譯 add(如果尚未構建)。 ./add 執行 add 可執行檔案。@ 用於抑制輸出。其他程式與此類似。
- clean 目標用於刪除已編譯的可執行檔案。
以下是 C 語言中加法、減法、乘法和除法程式。
程式檔案
add.c
#include <stdio.h> int main() { int a, b; printf("Enter two integers to add: "); scanf("%d %d", &a, &b); printf("Sum: %d
", a + b); return 0; }
sub.c
#include <stdio.h> int main() { int a, b; printf("Enter two integers to subtract: "); scanf("%d %d", &a, &b); printf("Difference: %d
", a - b); return 0; }
mul.c
#include <stdio.h> int main() { int a, b; printf("Enter two integers to multiply: "); scanf("%d %d", &a, &b); printf("Product: %d
", a * b); return 0; }
div.c
#include <stdio.h> int main() { int a, b; printf("Enter two integers to divide: "); scanf("%d %d", &a, &b); if (b != 0) printf("Quotient: %d
", a / b); else printf("Error: Division by zero.
"); return 0; }
此 Makefile 及其相關程式位於同一個目錄下。
執行 make 以執行特定操作。
廣告