2013-02-13 92 views
0

我需要一个Makefile来编译当前目录下的所有东西,并递归下去,最好使用编译器的依赖关系(-M等),这样每当我键入“make”时,尽可能少地重新编译。大型C++项目的Makefile模板?

此外,为什么这不是Makefile文档的第1页?

回答

8

虽然我会建议使用像cmake或类似的工具,但我知道有时使用普通的旧Makefile会更容易或更好。

下面是我的一些项目中使用的一个Makefile文件,它会创建使用gcc依赖性的文件:

# Project Name (executable) 
PROJECT = demoproject 
# Compiler 
CC = g++ 

# Run Options  
COMMANDLINE_OPTIONS = /dev/ttyS0 

# Compiler options during compilation 
COMPILE_OPTIONS = -ansi -pedantic -Wall 

#Header include directories 
HEADERS = 
#Libraries for linking 
LIBS = 

# Dependency options 
DEPENDENCY_OPTIONS = -MM 

#-- Do not edit below this line -- 

# Subdirs to search for additional source files 
SUBDIRS := $(shell ls -F | grep "\/") 
DIRS := ./ $(SUBDIRS) 
SOURCE_FILES := $(foreach d, $(DIRS), $(wildcard $(d)*.cpp)) 

# Create an object file of every cpp file 
OBJECTS = $(patsubst %.cpp, %.o, $(SOURCE_FILES)) 

# Dependencies 
DEPENDENCIES = $(patsubst %.cpp, %.d, $(SOURCE_FILES)) 

# Create .d files 
%.d: %.cpp 
    $(CC) $(DEPENDENCY_OPTIONS) $< -MT "$*.o $*.d" -MF $*.d 

# Make $(PROJECT) the default target 
all: $(DEPENDENCIES) $(PROJECT) 

$(PROJECT): $(OBJECTS) 
    $(CC) -o $(PROJECT) $(OBJECTS) $(LIBS) 

# Include dependencies (if there are any) 
ifneq "$(strip $(DEPENDENCIES))" "" 
    include $(DEPENDENCIES) 
endif 

# Compile every cpp file to an object 
%.o: %.cpp 
    $(CC) -c $(COMPILE_OPTIONS) -o [email protected] $< $(HEADERS) 

# Build & Run Project 
run: $(PROJECT) 
    ./$(PROJECT) $(COMMANDLINE_OPTIONS) 

# Clean & Debug 
.PHONY: makefile-debug 
makefile-debug: 

.PHONY: clean 
clean: 
    rm -f $(PROJECT) $(OBJECTS) 

.PHONY: depclean 
depclean: 
    rm -f $(DEPENDENCIES) 

clean-all: clean depclean 
+0

尼斯。我在include之前放了一个(并将缩进更改为制表符)以使其工作。 – 2013-02-14 21:39:54