Search code examples
makefilegnu-makegnuunix-ar

GNU Make: Using the wildcard function with implicit rules


I have a project structure that looks something like this:

.
└── src
    ├── Module1
    │   ├── source1.cc
    │   ├── source2.cc
    │   └── source3.cc
    ├── Module2
    │   ├── source1.cc
    │   ├── source2.cc
    │   └── source3.cc
    └── Module3
        ├── source1.cc
        ├── source2.cc
        └── source3.cc

I have an implicit rule that will create an object file for each source file, and maintain the directory structure (e.g. src/Module1/source2.cc would compile to obj/Module1/source2.o).

However, I would now like to have an implicit rule to create archive files for each module. For example, each object file compiled from src/Module2 would be added to obj/Module2.a. My first idea looked quite similar to my implicit rule for object files:

obj/%.a: $(wildcard obj/%/*.o)
    @mkdir -p $(@D);
    ar -crs "$@" $^;

This would pass off the work of compiling the object files to the other implicit rule. However, the issue here is that the % character is not expanded.

Is there a way to access the % from the implicit rule within the wildcard function call?


Solution

  • You can do it with Secondary Expansion:

    .SECONDEXPANSION:
    obj/%.a: $$(wildcard obj/%/*.o)
        @mkdir -p $(@D);
        ar -crs "$@" $^;