單一檔案的 C/C++ 用 gcc/g++ 一行就編完,但專案一拆成多個模組後,該怎麼編、怎麼連結,才是真正需要弄懂的部分。
C 版本 file1.c:
#include <stdio.h>
int main() {
printf("hello\n");
return 0;
}
C++ 版本 file1.cpp:
#include <iostream>
using namespace std;
int main() {
cout << "hello" << endl;
return 0;
}
$ gcc file1.c -o file1 $ g++ file1.cpp -o file1_cpp $ ./file1 hello $ ./file1_cpp hello
拆成標頭檔與實作檔 four 支檔案。 first.h:
int first();
first.c:
#include "include.h"
#include "first.h"
first() {
printf("this is just a test!");
return 0;
}
second.h:
int mymax(int,int);
second.c:
mymax(x,y) {
if(x>y) return x;
else return y;
}
main.c:
#include "first.h"
#include "second.h"
#include <stdio.h>
int main() {
int a,b;
a=10;
b=20;
first();
printf("%d\n",mymax(a,b));
return 0;
}
先各自編譯成目的檔,再一起連結:
$ gcc -c first.c $ gcc -c second.c $ gcc -c main.c $ gcc first.o second.o main.o -o main $ ./main this is just a test!20
也可以一次編完:
$ gcc first.c second.c main.c -o main
三支檔案手打還撐得住,模組一多,每次都重編全部實在折磨。此時應把編譯規則寫進 Makefile,之後只要一句 make,它會依據各檔案的時間戳判斷哪些需要重編,只處理有變動的部分。