将makefile目标组合成一个更可重用的目标

时间:2015-11-03 20:15:42

标签: makefile

我的Makefile定义了以下宏:

# Output location
OUT_DIR = Build

# Source location
SOURCE_DIR = Src

# Complete list of source files to be compiled
SOURCES  = $(SOURCE_DIR)/main.c
SOURCES += $(SOURCE_DIR)/startup.s
SOURCES += System/CMSIS/Device/ST/STM32F4xx/Source/Templates/system_stm32f4xx.c

# Separate out .c and .s source files
C_SOURCES = $(filter %.c, $(SOURCES))
ASM_SOURCES = $(filter %.s, $(SOURCES))

# Rename .c to .o, and replace the path with $(OUT_DIR)/
# For example Src/main.c becomes Build/main.o
OBJECTS  = $(addprefix $(OUT_DIR)/, $(notdir $(C_SOURCES:.c=.o)))
OBJECTS += $(addprefix $(OUT_DIR)/, $(notdir $(ASM_SOURCES:.s=.o)))

......我有以下目标让我烦恼:

$(OUT_DIR)/%.o : $(SOURCE_DIR)/%.c
    @echo "Compiling $<"
    $(CC) $(CFLAGS) $(INCLUDES) $(DEFINES) $< -o $(OUT_DIR)/$(notdir $@)
    @echo

$(OUT_DIR)/%.o : System/CMSIS/Device/ST/STM32F4xx/Source/Templates/%.c
    @echo "Compiling $<"
    $(CC) $(CFLAGS) $(INCLUDES) $(DEFINES) $< -o $(OUT_DIR)/$(notdir $@)
    @echo

有没有办法让目标定义一个,而不必指定路径?好像重复太多......

目标都很好,但我觉得重复这样的目标是不必要的。

1 个答案:

答案 0 :(得分:1)

您可以使用包含配方正文的Canned Recipe并在每个规则中使用它,但不能组合具有狂野不同先决条件模式的规则。

define JVN_COMPILE
    @echo "Compiling $<"
    $(CC) $(CFLAGS) $(INCLUDES) $(DEFINES) $< -o $(OUT_DIR)/$(notdir $@)
    @echo
endef

$(OUT_DIR)/%.o : $(SOURCE_DIR)/%.c
    $(JVN_COMPILE)

$(OUT_DIR)/%.o : System/CMSIS/Device/ST/STM32F4xx/Source/Templates/%.c
    $(JVN_COMPILE)

或者,设置VPATH并执行以下操作:

VPATH = Src:System/CMSIS/Device/ST/STM32F4xx/Source/Templates

define JVN_COMPILE
    @echo "Compiling $<"
    $(CC) $(CFLAGS) $(INCLUDES) $(DEFINES) $< -o $(OUT_DIR)/$(notdir $@)
    @echo
endef

$(OUT_DIR)/%.o : %.c
    $(JVN_COMPILE)