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

cyb*_*gon 5 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) $@ $<"
Run Code Online (Sandbox Code Playgroud)

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

use*_*267 4

使用特定于目标的变量

虽然不是绝对必要的,但分隔标志对于管理构建选项有很大帮助,然后您可以使用特定于目标的变量附加来切换标志。当您使用它时,您也可以使用内置变量名称。

我还添加了依赖项生成 ( -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)
Run Code Online (Sandbox Code Playgroud)