Makefile 编译源文件列表

Tom*_*Tom 5 makefile

我有我希望 Makefile 编译的文件列表,每种源语言都有一个列表:

CFILES=  Src/Application/main.c  Src/Core/data.c  Lib/routines.c
ASFILES= Src/Application/startup.s  Lib/sqrt.s
Run Code Online (Sandbox Code Playgroud)

我希望所有输出都在一个目录中:

OBJDIR= output
Run Code Online (Sandbox Code Playgroud)

我该如何做相当于:

output/main.o     : Src/Application/main.c
    cc -c -o output/main.o Src/Application/main.c

output/data.o     : Src/Core/data.c
    cc -c -o output/data.o Src/Core/data.c

output/routines.o : Lib/routines.c
    cc -c -o output/routines.o Lib/routines.c

output/startup.o  : Src/Application/startup.s
    as -o output/startup.o Src/Application/startup.s

output/sqrt.o     : Lib/sqrt.s
    as -o output/sqrt.o  Lib/sqrt.s
Run Code Online (Sandbox Code Playgroud)

列表中每个文件的配方都是相同的。

输入文件位于各种不同的目录中,仅列出它们的文件名并使用搜索路径来查找它们是不可接受的,必须使用它们的显式路径。

输出文件名是源文件名的基本名称,扩展名更改为 o。不同源语言的列表之间不存在重复的基本名称。

我不想列出目标文件,这应该来自源列表。

我正在使用 gnu make,但是便携式解决方案的加分项。

Max*_*kin 3

像下面这样的事情可以做到:

all :

OBJDIR := output
CFILES  := Src/Application/main.c Src/Core/data.c Lib/routines.c
ASFILES := Src/Application/startup.s Lib/sqrt.s

target = ${OBJDIR}/$(patsubst %.s,%.o,$(notdir ${1}))
obj.c :=
obj.s :=
define obj
  $(call target,${1}) : ${1} | ${OBJDIR}
  obj$(suffix ${1}) += $(call target,${1})
  ${1} : ; mkdir -p `dirname $$@` && touch $$@ # Create the source for testing. Remove this.
endef

define SOURCES
  $(foreach src,${1},$(eval $(call obj,${src})))
endef

$(eval $(call SOURCES,${CFILES}))
$(eval $(call SOURCES,${ASFILES}))

all : ${obj.c} ${obj.s}

${obj.c} : % :
    @echo cc -c -o $@ $^; touch $@ # echo and touch are for testing. Remove these.

${obj.s} : % :
    @echo as -o $@ $^; touch $@ # echo and touch are for testing. Remove these.

${OBJDIR} :
    mkdir $@

.PHONY: all
Run Code Online (Sandbox Code Playgroud)

输出:

$ make 
make: Entering directory '/home/max/tmp'
mkdir -p `dirname Src/Application/main.c` && touch Src/Application/main.c # Create the source for testing. Remove this.
mkdir output
cc -c -o output/main.c Src/Application/main.c
mkdir -p `dirname Src/Core/data.c` && touch Src/Core/data.c # Create the source for testing. Remove this.
cc -c -o output/data.c Src/Core/data.c
mkdir -p `dirname Lib/routines.c` && touch Lib/routines.c # Create the source for testing. Remove this.
cc -c -o output/routines.c Lib/routines.c
mkdir -p `dirname Src/Application/startup.s` && touch Src/Application/startup.s # Create the source for testing. Remove this.
as -o output/startup.o Src/Application/startup.s
mkdir -p `dirname Lib/sqrt.s` && touch Lib/sqrt.s # Create the source for testing. Remove this.
as -o output/sqrt.o Lib/sqrt.s
make: Leaving directory '/home/max/tmp'
Run Code Online (Sandbox Code Playgroud)