參考原帖位址
測試程式如下
main.cpp
print.h#include "print.h"
int main()
print.cpp#include #include using namespace std;
void printhello();
#include "print.h"
void printhello()
首先是基本版的makefile
乙個hello:main.o print.o
#helloworld依賴main.o print.o兩個目標檔案
g++ -std=c++11 main.o print.o -o hello #編譯出helloworld可執行檔案。-o表示你指定 的目標檔名。-std=c++11
main.o: main.cpp print.h
g++ -c main.cpp -o main.o
print.o:print.cpp print.h
g++ -c print.cpp -o print.o #create print.o
clean:
rm *.o hello #執行makefile clean 會刪除.o檔案與生成的hello可執行程式
makefile
主要含有一系列的規則,如下:
a: b
(tab)
(tab)
每個命令行前都必須有
tab
符號。第二個是使用變數版
使用變數需要用$(var)引用objs = main.o print.o
cc = g++
cflags = -wall -o -g
hello:$(objs)
$(cc) $(objs) -o hello
main.o:main.cpp print.h
$(cc) $(cflags) -c main.cpp -o main.o
print.o:print.cpp print.h
$(cc) $(cflags) -c print.cpp -o print.o
clean:
rm -rf *o hello
-wall 意思為列出所有警告
-o 為啟用優化
-g 為編譯debug版本
接下來是函式版本
cc = gcc
xx = g++
cflags = -wall -o -g
target = ./hello
#compile all .c and .cpp to .o
%.o:%c
$(cc) $(cflags) -c $< -o $@
%.o:%.cpp
$(xx) $(cflags) -c $< -o $@
sources = $(wildcard *.c *.cpp)
objs = $(patsubst %.c,%.o, $(patsubst %.cpp,%.o,$(sources)))
$(target):$(objs)
$(xx) $(objs) -o $(target)
chmod a+x $(target)
clean:
rm -rf *.o hello
其中有兩個函式:
1.wildcard: *** = $(wildcard a b) 表示將所有包含a 和b 的檔案生成乙個列表,存在變數***中
程式中為將所有含有.c 與.cpp 的檔案的列表存在變數sources中
2.patsubst: ttt = $(patsubst %a, %b, ***) 表示將變數***中所有的a替換為b,儲存在變數ttt中
程式中為將所有.c 與.cpp 替換為.o
3.foreach
: *** = $(foreach var, list, text)
表示從list獲取乙個以空格分割的單詞傳給臨時變數var,然後執行text表示式由其處理,完成後輸出,輸出結果為text處理完成後以空格為分割的處理結果。
例子如下,結果為返回dirs內的每個資料夾下包含的.c檔案的列表。
dirs = sub add ./
files = $(foreach dir, $(dirs), $(wildcard $(dir)/*.c))
其中有用的內部變數:
1.$@:擴充套件成當前規則的檔名
2.$<:擴充套件成依靠 列表中第乙個依靠檔案
3.$^:擴充套件成整個依靠的列表(除掉了裡面所有重複的檔名)
chmod a+x $(target)表示將target強制變為可執行檔案
例項學習編寫Makefile
1.test1.c包含主函式main的檔案 include int main 2a.test2 test2.c目錄下子檔案 include include test2.h int test2 func void 2b.test2 test2.h define test num 3 3a.test t...
makefile簡說 編寫makefile
linux下原始碼編譯 linux下原始碼編譯c c 通常使用gnu工具鏈。c c 的編譯過程,通常為原始檔 c cc cpp字尾檔案 編譯為中間目標檔案 即生成為.s o等字尾的中間檔案 再通過鏈結生成可執行檔案 編譯器的編譯過程大致分為四個步驟 預處理 編譯 彙編和鏈結 建立乙個專案檔案proj...
makefile編寫說明
1.定義 makefile是通過制定規則來編譯程式的乙個指令碼而已。在linux中使用make命令來執行makefile檔案。2.命名 makefile或makefile,若是指定其他名稱。如 makefile.可以這樣使用make f makefile或make clean f makefile ...