根據老師的要求,寫一個超簡單的makefile
准備:
准備三個文件:file1.c, file2.c, file2.h
file1.c:
#include "file2.h" int main() { printf("print file1$$$$$$$$$$$$$$$$$$$$$$$$\n"); File2Print(); return 0; }
file2.h:
#include <stdio.h> #ifndef FILE2_H_ #define FILE2_H_ #ifdef __cplusplus extern "C" { #endif void File2Print(); #ifdef __cplusplus } #endif #endif
file2.c:
#include "file2.h" void File2Print() { printf("Print file2**********************\n"); }
基礎:
先來個例子:
有這么個Makefile文件。(文件和Makefile在同一目錄)
=== makefile 開始 ===
helloworld:file1.o file2.o gcc file1.o file2.o -o helloworld file1.o:file1.c file2.h gcc -c -o file1.o file1.c file2.o:file2.c file2.h gcc -c -o file2.o file2.c
一個 makefile 主要含有一系列的規則,如下:
目標文件:依賴文件
(tab)<command>
(tab)<command>
每個命令行前都必須有tab符號。
上面的makefile文件目的就是要編譯一個helloworld的可執行文件。讓我們一句一句來解釋:
helloworld : file1.o file2.o: helloworld依賴file1.o file2.o兩個目標文件。
gcc file1.o file2.o -o helloworld: 編譯出helloworld可執行文件。-o表示你指定 的目標文件名。
file1.o : file1.c file2.h: file1.o依賴file1.c文件。
gcc -c file1.c -o file1.o:編譯出file1.o文件。-c表示gcc 只把給它的文件編譯成目標文件, 用源碼文件的文件名命名但把其后綴由“.c”或“.cc”變成“.o”。在這句中,可以省略-o file1.o,編譯器默認生成file1.o文件,這就是-c的作用。
file2.o : file2.c file2.h
gcc -c file2.c -o file2.o
這兩句和上兩句相同。
如果要編譯cpp文件,只要把gcc改成g++就行了。
寫好Makefile文件,在命令行中直接鍵入make命令,就會執行Makefile中的內容了。
結果如圖:
另附好博鏈接:http://goodcandle.cnblogs.com/archive/2006/03/30/278702.html
http://blog.csdn.net/liang13664759/article/details/1771246