2016-04-27 47 views
4

我正在尋找編寫一個makefile來自動編譯我正在編寫的項目,文件可能會更改或不更改編號。我還需要能夠快速地告訴make將文件編譯爲調試版本或發佈版本(通過命令行定義進行區分)。經過一番研究,我發現了模式規則,並制定了一個規則。這裏是我的代碼至今:如何在makefile中的其他規則中運行模式規則?

# Our folders 
# ODIR - The .o file directory 
# CDIR - The .cpp file directory 
# HDIR - The .hpp file directory 
ODIR = obj 
CDIR = src 
HDIR = inc 

# Get our compiler and compiler commands out of the way 
# CC - Our compiler 
# CFNO - Our compiler flags for when we don't have an output file 
# CF - Our compiler flags. This should be appended to any compile and should 
#   have the name of the output file at the end of it. 
# OF - Object flags. This should be appended to any line that is generating 
#   a .o file. 
CC = g++ 
CFNO = -std=c++11 -wall -Wno-write-strings -Wno-sign-compare -lpaho-mqtt3c -pthread -O2 -I$(HDIR) 
CF = $(CFNO) -o 
OF = -c 

# Our project/output name 
NAME = tls_test 

# Set out Debug and Release settings, as well as any defines we will use to identify which mode we are in 
# NOTE: '-D[NAME OF DEFINE]' is how you create a define through the compile commands 
DEBUG = -DDEBUG -g 
RELEASE = -DRELEASE 

# Our two compile modes 
# eval allows us to create variables mid-rule 
debug: 
    $(eval DR = $(DEBUG)) 

release: 
    $(eval DR = $(RELEASE)) 

# Our compiling commands 
all: 
    $(CC) $(CF) $(NAME) $(ODIR)/*.o 

# NOTE: [email protected] is the end product being created and $< is the first of the prerequisite 
$(ODIR)/%.o: $(CDIR)/%.c 
    echo "$(CC) $(DR) $(OF) $(CF) [email protected] $<" 

,我有是有順序,我需要的東西來運行這一問題的命令行調用應該告訴make使用調試或釋放,這臺一個make變量,然後全部調用。所有人都應該在運行當前所有規則中的行之前在底部運行模式規則。那麼,如何使模式規則成爲依賴關係,以及如何從另一個規則調用規則?

+0

你想讓Make編譯'src /'中的所有源文件(帶有適合構建的標誌),然後將所有生成的目標文件鏈接到可執行文件中,是嗎? – Beta

回答

3

使用特定目標變量

雖然不是絕對必要,分離的標誌去管理構建選項,就可以使用target-specific variable追加切換標誌很長的路要走。當你在它的時候,你可能會使用內置的變量名稱。

我也添加了依賴關係生成(-MMD -MP),因爲它總是有用的。

ODIR := obj 
CDIR := src 
HDIR := inc 

SRCS := $(wildcard $(CDIR)/*.cpp) 
OBJS := $(SRCS:$(CDIR)/%.cpp=$(ODIR)/%.o) 
DEPS := $(OBJS:%.o=%.d) 

CPPFLAGS := -I$(HDIR) -MMD -MP 
CXXFLAGS := -std=c++11 -Wall -Wno-write-strings -Wno-sign-compare -pthread -O2 
LDFLAGS := -pthread 
LDLIBS := -lpaho-mqtt3c 

NAME := tls_test 

.PHONY: debug release clean 

debug: CPPFLAGS+=-DDEBUG 
debug: CXXFLAGS+=-g 

release: CPPFLAGS+=-DRELEASE 

debug release: $(NAME) 

$(NAME): $(OBJS) 
    $(CXX) $(LDFLAGS) $^ $(LDLIBS) -o [email protected] 

$(OBJS): $(ODIR)/%.o: $(CDIR)/%.cpp 
    $(CXX) $(CXXFLAGS) $(CPPFLAGS) -c $(OUTPUT_OPTION) $< 

clean: ; $(RM) $(NAME) $(OBJS) $(DEPS)  

-include $(DEPS) 
+0

我可以猜出你想要的'OUTPUT_OPTION'是什麼,但你應該拼出來。 – Beta

+0

@Beta爲什麼,默認爲'-o $ @'。 – user657267

+0

我站好了。我不知道這個變量,但現在我知道了,我沒有看到它讓這個makefile更容易理解或維護。 – Beta