Makefile 编译多个具有 main 功能的程序时出现一个 makefile 错误

Makefile compile many programs with main function with one makefile error

我正在尝试使用一个 Makefile 来编译多个 .c 文件。我已经写了所有的规则,我想添加一条规则说:执行所有依赖.c 文件的规则。

参考:Compile all C files in a directory into separate programs

PROGRAMS := copy.c sec_soft.c
PROGRAMS_NO_EX := $(basename $(PROGRAMS))
PROGRAMS_TO_CREATE := $(PROGRAMS_NO_EX).elf $(PROGRAMS_NO_EX).dump $(PROGRAMS_NO_EX).bin $(PROGRAMS_NO_EX).hex $(PROGRAMS_NO_EX).mem  $(PROGRAMS_NO_EX).coe

RISCV_OPTIONS = -march=rv32if -mabi=ilp32 -o  
RISCV_LINK = $(RISCV_GCC) $(CFLAGS) $< -o $@                            #produces .elf file!
RISCV_OBJDUMP = $(RISCV_PREFIX)objdump -D   $(DFLAGS)                       #produces a dump file to see the assembly code!
RISCV_OBJCOPY = $(RISCV_PREFIX)objcopy -O binary                        #produces a bin file!

ALL_RES = $(PROGRAMS:%.c=%.elf)

%.elf: %.c
    $(info Generating .elf file from files: $(PROGRAMS_NO_EX))
    $(RISCV_LINK)
    $(info Success!)
    $(info ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~)
%.dump: %.elf
    $(info Copying assembly to dump file $(PROGRAMS_NO_EX).dump)
    @$(RISCV_OBJDUMP) $< > $@
    $(info Success!)
    $(info ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~)
%.bin: %.elf
    $(info Generating bin file)
    @$(RISCV_OBJCOPY) $< $@
    $(info Success!)
    $(info ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~)
%.hex: %.bin 
    $(info Generating hex file)
    echo cd $(SCRIPTDIR)
    $(info Running binary to hex >>>)
    python $(SCRIPTDIR)/bin2hex.py -a $(START_ADDRESS) -o $@ $<
    $(info Hex Generation Successful!)
    $(info ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~)
%.mem: %.bin
    $(info Instantiating memory addresses...)
    head -c $$(( $(START_ADDRESS))) /dev/zero | cat - $< | xxd -g1 -c4 | awk '{print $$$$}' > $@
    $(info Memory instantiation Successful!)
    $(info ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~)
%.coe: %.bin
    $(info Instantiating memory vector...)
    python $(SCRIPTDIR)/bin2coe.py $< -o $@
    $(info Memory vector instantiation Successful )
    $(info ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~)    

all: $(ALL_RES);

但是这一行ALL_RES = $(PROGRAMS:%.c=%.elf)并没有执行所有的规则。我希望在生成 .elf 文件后,下面的所有规则都会执行,但不会执行。

我是 Makefile 新手,如有错误请多多包涵。

提前致谢

make 不会创建您没有要求的目标。您的 all 目标只要求创建扩展名为 .elf 的文件,仅此而已。如果你想构建所有其他的,你应该告诉 make 这样做。

构建目标的定义应该更新,因为它没有正确创建文件名。按原样编写,它仅将扩展连接到变量的末尾。自己看看:

$ make -rp 2>&1 | grep PROGRAMS_TO_CREATE
PROGRAMS_TO_CREATE := copy sec_soft.elf copy sec_soft.dump copy sec_soft.bin copy sec_soft.hex copy sec_soft.mem  copy sec_soft.coe

这应该更新为正确的字符串操作,例如:

PROGRAMS_TO_CREATE := $(foreach program,$(PROGRAMS_NO_EX),$(addprefix $(program),.elf .dump .bin .hex .mem .coe))

这将生成正确的目标列表:

$ make -rp 2>&1 | grep PROGRAMS_TO_CREATE
PROGRAMS_TO_CREATE := copy.elf copy.dump copy.bin copy.hex copy.mem copy.coe sec_soft.elf sec_soft.dump sec_soft.bin sec_soft.hex sec_soft.mem sec_soft.coe

设置为对目标的依赖后 all:

all: $(PROGRAMS_TO_CREATE)

将导致正确构建。