c++ - 大型 C++ 项目的 Makefile 模板?

标签 c++ makefile

我需要一个 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

关于c++ - 大型 C++ 项目的 Makefile 模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14844268/

相关文章:

c++ - 在模板类 C++ 中使用模板类

c++ - 是否可以根据type_info创建对象?

c++ - 创建一个单词移位器

c - 多个目录和多个源中的 Makefile

c++ - HWLOC 链接错误

c++ - 专门针对模板类的 C++ 类成员函数

c++ - 在递归函数c++中保持原始值

Android JB 4.2.2 编译错误

生成文件 : reading a file with 'pure make syntaxis' (no shell commands)

makefile - GNU make - 强制 PHONY 目标的依赖顺序