makefile - 如何在 makefile 中的另一个规则中运行模式规则?

标签 makefile gnu-make

我正在寻找编写一个 makefile 来自动编译我正在处理的项目,其中文件的数量可能会或可能不会改变。我还需要能够快速告诉 make 将文件编译为调试版本或发布版本(由命令行定义区分)。经过一番研究,我发现了模式规则并做了一个。这是我到目前为止的代码:

# 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: $@ is the end product being created and $< is the first of the prerequisite
$(ODIR)/%.o: $(CDIR)/%.c
    echo "$(CC) $(DR) $(OF) $(CF) $@ $<"

我遇到的问题是我需要运行的顺序。命令行调用应该告诉 make 使用 debug 或 release,它设置一个 make 变量,然后调用 all。 all 然后应该在运行 all 规则中当前的行之前运行底部的模式规则。那么,如何使模式规则成为依赖项,以及如何从另一个规则调用规则?

最佳答案

使用特定于目标的变量

虽然不是绝对必要的,但分离你的标志对管理构建选项大有帮助,然后你可以使用 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 $@

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

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

-include $(DEPS)

关于makefile - 如何在 makefile 中的另一个规则中运行模式规则?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36902684/

相关文章:

makefile - 使用 GNU Make 构建分层 Makefile

makefile - 我如何在makefile中用点分割字符串

r - 如何在 R CMD 构建中使用 Makefile

c++ makefile项目如何创建具有相同基本名称加上后缀和相同扩展名的文件列表

c++ - 如何将 -Wno-unused-private-field 添加到一个文件中?

c++ - 使库名称成为 make 中包含路径的一部分?

makefile - 如何在 makefile 中写入 'cd' 命令?

maven - 多语言项目构建系统

makefile - 停止让它回显进入/退出的目录

c - "make target"在 "make clean"之后不工作