編碼的世界 / 優質文選 / 財富

Windows安裝GNU編譯器使用makefile


2021年10月04日
-   

Windows安裝GNU編譯器使用makefile

一、下載安裝MinGW


MinGW下載網頁:http://sourceforge.net/projects/mingw/files/latest/download?source=files

下載後,運行程序:mingw-get-inst-20120426.exe,選擇download latest repository catalogues. 選擇編譯器是勾選C Compiler 與C++ Compiler,點擊next進行下載及安裝。

二、設置環境變量


右擊計算機->屬性->高級系統設置->環境變量,在系統變量中找到PATH,將MinGW安裝目錄裏的bin文件夾的地址添加到PATH裏面,(注意:PATH裏兩個目錄之間以英文的;隔開)。打開MinGW的安裝目錄,打開bin文件夾,將mingw32-make.exe重命名為make.exe。

三、測試GCC編譯


創建一下test.c,用記事本打開該文件,將以下內容複制到文件中。
#include<stdio.h>
#include<stdlib.h>
int main(void){
printf("Hello, world!
");
system("pause");
return 0;
}

打開命令提示符,更改目錄到test.c的位置,鍵入
gcc -o test.exe test.c
可生成test.exe可執行文件。

四、測試makefile


新建文件夾,在文件夾內創建max_num.c、max.h、max.c、makefile四個文件。
max_num.c內容如下:
#include <stdio.h>
#include <stdlib.h>
#include "max.h"
int main(void)
{
printf("The bigger one of 3 and 5 is %d
", max(3, 5));
system("pause");
return 0;
}

max.h內容如下:
int max(int a, int b);

max.c內容如下:
#include "max.h"
int max(int a, int b)
{
return a > b ? a : b;
}

makefile內容如下:
max_num.exe: max_num.o max.o
gcc -o max_num.exe max_num.o max.o
max_num.o: max_num.c max.h
gcc -c max_num.c
max.o: max.c max.h
gcc -c max.c

注意所有含有gcc的行前面是一個制表符,而非若幹空格。否則可能會保存,無法編譯。
打開命令提示符,更改目錄到新建的文件夾,鍵入make,可生成指定的應運程序。
測試完成。

熱門文章