我需要一个 Makefile,它将编译当前目录中的所有内容并递归地沿树向下,并且最好使用编译器的依赖项(-M 等),以便每当我键入“make”时,都会尽可能少地重新编译。
另外,为什么这不是 Makefile 文档的第 1 页?
虽然我建议使用 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 $@ $< $(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