Search code examples
makefilegnu-makekeil

Create object files in one folder from different source folders


I am creating a Makefile of a Keil based project. I have a working Makefile now, but I have manually written rules for all the source files, something like this:

out/abc.o: ../../../src/modules/abc.c
       ARMCC -o $@ $(FLAGS) $^ 
out/def.o: ../../../src/utilities/def.c
       ARMCC -o $@ $(FLAGS) $^ 
out/xyz.o: src/xyz.c
       ARMCC -o $@ $(FLAGS) $^ 

which has become kinda long. The object files need to be in one directory(/out), but the source files are in different levels and in various folders like utilities, modules etc. Is there a way to shorten my Makefile so that it scans these different levels of source files and creates the object files?

EDIT: A follow-up question to the answer. My linker rule is something like this, along with the VPATH addition. I added one directory to VPATH and others are still explicitly compiled.

OBJECT_FILES=out/abc.o out/def.o out/xyz.o

out/binary.axf: $(OBJECT_FILES)
               ARMLINK $(MANY_FLAGS) $^ -o $@
VPATH=../a/b/c/module
out/%.o : %.c
        $(CC) $(C_FLAGS) $(INCLUDE_PATH) -o $@ --depend out/%.d $<

I now get an error that there is no rule for abc.o. abc.c which is present in the directory specified in VPATH under module

*** No rule to make target `out/abc.o', needed by `out/binary.axf'.  Stop.

Solution

  • You can use VPATH for this. It can search a list of directories for source files. Assuming you can come up with the list of directories:

    VPATH = ../../../src src
    
    CC = ARMCC
    
    out/%.o : %.c
            $(CC) -o $@ $(CFLAGS) -c $<