用于构建.o文件的递归Makefile

时间:2018-03-21 15:46:10

标签: c++ makefile

我正在编写一个简单的内核,到目前为止一切顺利。 我正在使用Makefile通过shell构建系统。 但是,我希望移动并重新组织文件结构,但是我的makefile使用绝对链接。 如何重构这个以将所有.cpp/.c文件和.s文件编译到out文件夹并链接它们,而无需定义每个文件夹路径?

CC = ~/opt/cross/bin/i386-elf-g++
AS = ~/opt/cross/bin/i386-elf-as
LNFLAGS = -T linker.ld -melf_i386
CCFLAGS = -c -ffreestanding -nostdlib -fno-builtin -fno-rtti -fno-exceptions
ASFLAGS = -c
CTMP = $(wildcard src/kernel/*.cpp)
ATMP = $(wildcard src/kernel/arch/i386/*.s)
CFILE = $(subst src/kernel/, ,$(CTMP))
AFILE = $(subst src/kernel/arch/i386/, ,$(ATMP))
CSRC = $(CFILE:.c=)
ASRC = $(AFILE:.s=)

OUT = $(wildcard out/*.o)

all: ccompile acompile link

ccompile:
    for file in $(CSRC) ; do \
        $(CC) $(CCFLAGS) src/kernel/$$file -o out/$$file.o ; \
    done

acompile:
    for file in $(ASRC) ; do \
        $(AS) $(ASFLAGS) src/kernel/arch/i386/$$file.s -o out/$$file.o ; \
    done

link:
    ld $(LNFLAGS) -o latest.bin $(OUT)

1 个答案:

答案 0 :(得分:0)

使用vpath指令指定源目录。

TARGETS := latest.bin

LD      := ld
LDFLAGS := -T linker.ld -melf_i386

CC      := ~/opt/cross/bin/i386-elf-g++
CCFLAGS := -c -ffreestanding -nostdlib -fno-builtin -fno-rtti -fno-exceptions

AS      := ~/opt/cross/bin/i386-elf-as
ASFLAGS := -c

vpath %.cpp  src/kernel
vpath %.s    src/kernel/arch/i386

SOURCES := $(wildcard *.cpp) $(wildcard *.s)
OBJECTS := $(addsuffix .o, $(basename $(notdir $(SOURCES))))

all: $(TARGETS)

out/%.o: %.cpp
    $(CC) $(CCFLAGS) -o $@ $<

out/%.o: %.s
    $(AS) $(ASFLAGS) -o $@ $<

latest.bin: $(OBJECTS)
    $(LD) $(LDFLAGS) -o $@ $^