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

标签 makefile gnu-make sdcc

我创建了一个像这样的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 中执行此操作?

最佳答案

根据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 自己计算出如何组合这些规则,从源代码到最终程序(或从您教它构建的目标中指定的任何其他目标)。

关于makefile - 使用 make 对每个源文件执行操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39645042/

相关文章:

makefile - 如何对 GNU Make 文件进行性能分析

C: "undefined reference to"和 collect2: error: ld 返回 1 退出状态

interrupt - 无法弄清楚如何使用 SDCC 为 Z80 编写中断处理程序

c - 如何将变量放在 SDCC 中的特定内存位置

vim - 在不退出 Vim 的情况下调用不同目录中的 Makefile

c++ - 使用 make 构建时在 C++ 文件中泛化 include 语句

linux - 使用 makefile 进行编译的多个 SRCDIR 文件夹

c++ - gmake 覆盖编译器目录

bash - Makefile 符号 $= 是什么意思?

c - 您如何控制 C 编译器优化的内容?