使用 make 对每个源文件执行操作

Performing an action over each source file with make

我创建了一个这样的 Makefile

CC = sdcc
SRCS = $(PNAME).c\
    ../../src/gpio.c
    ../../src/timers.c
    ../../src/i2c.c
$HDRS = -I../../headers

all:
    mkdir -p ./output
    $(CC) $(SRCS) -lstm8 -mstm8 $(HDRS)

问题是,sdcc一次只能编译一个源代码。所以我需要对我在 SRCS 变量中定义的每个源执行类似 foreach 的操作。如何在 gnu-make 中执行此操作?

使用patsubst。通常是这样的:

SOURCES := $(wildcard *.c)
OBJECTS := $(patsubst %.c,%.o,${SOURCES})
prog: ${OBJECTS}
        cc $^ -o $@
%.o: %.c
        cc $< -c -o $@

根据the docs,您必须单独编译包含main()的文件以外的文件,以生成.rel个文件,然后将这些文件包含在主文件的编译命令中.关于如何做到这一点有多种变体。以下避免了特定于 GNU make 的功能:

# We're assuming POSIX conformance
.POSIX:

CC = sdcc

# In case you ever want a different name for the main source file    
MAINSRC = $(PMAIN).c

# These are the sources that must be compiled to .rel files:
EXTRASRCS = \
    ../../src/gpio.c \
    ../../src/timers.c \
    ../../src/i2c.c

# The list of .rel files can be derived from the list of their source files
RELS = $(EXTRASRCS:.c=.rel)

INCLUDES = -I../../headers
CFLAGS   = -mstm8 
LIBS     = -lstm8 

# This just provides the conventional target name "all"; it is optional
# Note: I assume you set PNAME via some means not exhibited in your original file
all: $(PNAME)

# How to build the overall program
$(PNAME): $(MAINSRC) $(RELS)
    $(CC) $(INCLUDES) $(CFLAGS) $(MAINSRC) $(RELS) $(LIBS)

# How to build any .rel file from its corresponding .c file
# GNU would have you use a pattern rule for this, but that's GNU-specific
.c.rel:
    $(CC) -c $(INCLUDES) $(CFLAGS) $<

# Suffixes appearing in suffix rules we care about.
# Necessary because .rel is not one of the standard suffixes.
.SUFFIXES: .c .rel

顺便说一句,如果你仔细看,你会发现该文件没有明确地对源文件执行任何循环,或任何类似的事情。它只是描述了如何构建每个目标,包括中间目标。 make 自行找出如何组合这些规则以从源代码到最终程序(或从您教它构建的目标中指定的任何其他目标)。