1. 程式人生 > >Makefile條件編譯debug版和release版

Makefile條件編譯debug版和release版

原文地址為: Makefile條件編譯debug版和release版

一般,在開發測試階段用debug版本,而上線釋出用release版本。

使用Makefile定製編譯不同版本,避免修改程式和Makefile檔案,將會十分方便。

讀了一些資料,找到一個解決方法,Makefile預定義巨集與條件判斷,結合make預定義變數,進行條件編譯。

 

比如,有一個test.cpp,包含這段程式碼

#ifdef debug
//your code
#endif

你希望在debug版本要執行它,在release版本不執行。

我們可以寫這樣的一個Makefile:

 1
ver = debug
2
3 ifeq ($(ver), debug)
4 ALL: test_d
5 CXXFLAGS = -c -g -Ddebug
6 else
7 ALL: test_r
8 CXXFLAGS = -c -O3
9 endif
10
11 test_d: test.do
12 g++ -o [email protected] $^
13
14 test_r: test.ro
15 g++ -o [email protected] $^
16
17 %.do: %.cpp
18 g++ $(CXXFLAGS) $< -o [email protected]

19
20 %.ro: %.cpp
21 g++ $(CXXFLAGS) $< -o [email protected]

簡單說一下,Makefile根據ver的不同定義了不同的編譯選項CXXFLAGS與輸出程式ALL,

debug版本輸出程式是test_d,release版本輸出程式是test_r

debug版本編譯選項是"-c -g -Ddebug",release版本編譯選項是"-c -O3"

debug版本object檔案字尾是".do",release版本object檔案字尾是".ro"

debug版本編譯選項使用"-D"定義巨集debug,使得your code能夠執行。

不同版本的編譯選項、object檔案、輸出程式均不同,所以可以同時編譯兩個版本的程式,互不影響。

 

Makefile執行時,首先判斷ver變數,如果ver的值是debug,編譯debug版,否則編譯release版。當然,預設情況下是編譯debug版的。

如果想編譯release版,要怎麼做?

只要在執行make時,對ver變數賦值,使得ver的值不為debug,比如

# make ver=release

 

 

如有疏漏,歡迎指正!


轉載請註明本文地址: Makefile條件編譯debug版和release版