在剛開始學Java時用命令行進行編譯代碼。而C++一直在用IDE, 這次嘗試下命令行編譯。vs下也可以用cl.exe、link.exe等命令來進行編譯
但這次是通過安裝MinGW來學習命令編譯,主要用到g++。
(1)g++簡介
通過下面命令可查看g++版本
g++ -v
結果如下:
也可以通過g++ --help 查看更多的可用命令。
(2)編譯單個文件
編寫單個文件的可執行程序代碼hello.cpp如下

1 #include <iostream> 2 using namespace std; 3 4 int main(){ 5 cout << "Hello World!" << endl; 6 }
用cmd打開該文件所在的相應文件夾,並輸入:g++ hello.cpp
默認情況下,在該文件夾中將產生:a.exe, 此時在cmd中輸入a,就可以看到輸出結果。
我們也可以自定義產生的可執行程序名,如test.exe, 我們只要輸入:g++ hello.cpp -o test
然后就得到test.exe文件,在cmd中輸入test就能夠得到結果,實驗結果如下:
(3)編譯多個文件
定義頭文件header.h, 頭文件包含3個函數聲明:

int fact(int n); int static_val(); int mabs(int);
定義函數定義文件func.cpp:

#include "header.h" int fact(int n) { int ret = 1; while(n > 1) ret *= n--; return ret; } int static_val() { static int count = 1; return ++count; } int mabs(int n) { return (n > 0) ? n : -n; }
定義主函數文件main.cpp:

#include <iostream> #include "header.h" using namespace std; int main() { int j = fact(5); cout << "5! is " << j << endl; for(int i=1; i<=5; ++i) { cout << static_val() << " "; } cout << endl; cout << "mabs(-8) is " << mabs(-8) << endl; return 0; }
在同一個文件夾下編輯header.h,func.cpp,main.cpp后,就可以進行多個文件編譯,注意到在命令行編譯中似乎沒有頭文件什么事,
頭文件只是起到聲明的作用,因此只需編譯兩個*.cpp文件並鏈接就可以。
輸入下面兩行分別編譯兩個文件:
g++ -c func.cpp
g++ -c main.cpp
上面編譯完成后生成兩個文件:func.o,main.o
之后通過鏈接就可以得到最終的可執行程序,輸入下面命令:
g++ main.o func.o -o test
最終產生可執行程序test.exe, 可以直接在cmd中輸入驗證,結果如下:
ps: 似乎總在重復學習簡單的東西,希望系統學習復習整理后,能夠往前一步,學習更有趣、更高深的內容。