文中部分引用自:http://bbs.chinaunix.net/forum.php?mod=viewthread&tid=408225
windows下makefile環境配置見於:http://www.cnblogs.com/cvbnm/articles/1954872.html
最近我們的助教讓我們寫一個貪食蛇的小程序,雖然難度並不大,但卻對我們的整體編程能力的提高有一定的幫助,其中在他的提供的框架中用到了makefile,我之前代碼打了不少,但並沒有系統的學習編程,因此對makefile並不了解,今天在網上查了資料后發現windows下的makefile與linux下的makefile有一定的區別,經過幾次嘗試終於寫出了自己的第一個makefile,特此記下。
首先,單文件的makefile較為簡單,這里就不提了,主要是多文件的makefile較難掌握。
在我的文件中我寫了一下幾個文件:main.cpp, map.cpp, map.h, makefile(無后綴名,且此文件名不能更改)
main.cpp:
// 學習編程的小菜鳥 // http://www.cnblogs.com/zhuangshq/ #include <iostream> #include "map.h" using namespace std; int main() { cout << "Hello Makefile!" << endl; run(); return 0; }
map.cpp:
// 學習編程的小菜鳥 // http://www.cnblogs.com/zhuangshq/ #include <iostream> #include "map.h" #ifndef NULL #define NULL 0 #endif // NULL using namespace std; void run() { // loadMap(1); // printMap(); cout << "make success!" << endl; }
map.h:
// 學習編程的小菜鳥 // http://www.cnblogs.com/zhuangshq/ #ifndef MAP_H #define MAP_H // run void run(); #endif
makefile:
// 學習編程的小菜鳥 // http://www.cnblogs.com/zhuangshq/ test: main.o map.o g++ main.o map.o -o test main.o: main.cpp g++ -c main.cpp -o main.o map.o: map.cpp g++ -c map.cpp -o map.o clean: rm *.o *.exe
以上代碼實現在main.cpp中調用map.cpp中的run函數,在下面我們來分析makefile的內容:
根據makefile的語法,
target ... : prerequisites ...
command
...
...
target也就是一個目標文件,可以是Object File,也可以是執行文件。還可以是一個標簽(Label)。
prerequisites就是,要生成那個target所需要的文件或是目標。
command也就是make需要執行的命令。(任意的Shell命令)
那么我們的第一行生成的目標文件就是test.exe,而test.exe是由main.o和map.o生成的,接下來的兩個語段分別生成了main.o和map.o
接下來我們只需要在上述文件所在的文件夾中打開命令行窗口並執行nmake命令即可生成test.exe,執行nmake clean命令即可刪除生成的文件。