Search code examples
assemblymakefile

How can I compile all assembly files in a directory and its subdirectories using Makefile?


I am trying to create a makefile that will compile all the '.asm' files inside the 'src/kernel' directory and its subdirectories. I have been able to find all the files using the 'find' command, but I am having trouble creating the object files in the 'build' directory without creating subdirectories.

ASMSOURCES = $(shell find src/kernel -name '*.asm')
ASMOBJECTS = $(addprefix $(BUILD_DIR)/, $(notdir $(patsubst %.asm, %_asm.o, $(ASMSOURCES))))

$(ASMOBJECTS): $(BUILD_DIR)/%_asm.o : $(ASMSOURCES)
    $(ASM) $(ASFLAGS) $< -o $@

The above code correctly finds all the '.asm' files, but it creates the object files with the same file as much a the files in the src/kernel folder but with the correct names let me explain for exemple i have three files src/kernel/test1.asm src/kernel/something/file.asm and src/kernel/something2/something.asm i want to compile them to object files so that the output would be test1_asm.o for the first one file_asm.o for the second and something_asm.o for the third but in reality the src/kernel/test1.asm compile for test1_asm.o and file_asm.o and something_asm.o


Solution

  • The rule for compiling the objects:

    $(ASMOBJECTS): $(BUILD_DIR)/%_asm.o : $(ASMSOURCES)
     $(ASM) $(ASFLAGS) $< -o $@
    

    States that each object file depend on ALL sources files. The '$<' refers to the first item in ASMSOURCES. This is not what you want. You want each object file to depend on the corresponding '.asm' file, in the correct source folder.

    Trying to build the rule from the object list will be hard, as the object filename do not carry the source folder. As an alternative, consider building virtual path (vpath) to reference all the source folders.

    BUILD_DIR = build
    ASMSOURCES = $(shell find src/kernel -name '*.asm')
    ASMDIRS = $(sort $(dir $(ASMSOURCES)))
    ASMOBJECTS = $(addprefix $(BUILD_DIR)/, $(notdir $(patsubst %.asm, %_asm.o, $(ASMSOURCES))))
    
    all: $(ASMOBJECTS)
    
    vpath %.asm $(ASMDIRS)
    
    $(ASMOBJECTS): $(BUILD_DIR)/%_asm.o: %.asm
        $(AS) $(ASFLAGS) $< -o $@