$ vi hello.c
輸入:
#include <stdio.h>
int main(void) {
printf("Hello, Linux C World!\n");
return 0;
}
按 Esc → :wq 存檔離開。
$ gcc hello.c -o hello
gcc:GNU Compiler Collection-o hello:指定輸出執行檔名稱 (預設 a.out)$ ./hello
Hello, Linux C World!
故意移除分號:
$ gcc hello.c -o hello
hello.c: In function 'main':
hello.c:3:5: error: expected ';' before 'return'
return 0;
^~~~~~
編譯器會精確指出**檔案、行號、錯誤類型**,照著修正即可。
#include <stdio.h>
#include <stdlib.h>
int gcd(int a, int b) {
while (b) { int t = a % b; a = b; b = t; }
return a;
}
int main(void) {
int m, n;
printf("輸入兩個正整數: ");
if (scanf("%d %d", &m, &n) != 2) return 1;
printf("GCD(%d, %d) = %d\n", m, n, gcd(m, n));
return 0;
}
$ gcc gcd.c -o gcd
$ ./gcd
輸入兩個正整數: 48 18
GCD(48, 18) = 6
| 參數 | 用途 |
|---|---|
-Wall -Wextra | 開啟絕大多數警告 (強烈建議常開) |
-std=c11 | 指定 C 標準 (c90/c99/c11/c17/c2x) |
-g | 產生除錯資訊 (供 GDB 使用) |
-O2 | 優化等級 2 (發布版常用) |
-c | 僅編譯不連結,產生 .o 目標檔 |
-I/path | 加入標頭檔搜尋路徑 |
-L/path -lname | 加入程式庫搜尋路徑與連結 |