I use the -MM flag in GCC to generate makefile dependencies for objects. The makefile briefly looks like this:
-include autodep
...
$(TARGET): build $(OBJECTS)
    $(CC) -shared -o $@ $(OBJECTS)
    $(CC) -MM $(SOURCES) > autodep
The sources are located the in folder src. However, the autodep file will contain the object targets without their relative path:
foo.o: src/foo.c src/foo.h
bar.o: src/bar.c src/bar.h src/baz.h
How should I turn them into this:
src/foo.o: src/foo.c src/foo.h
src/bar.o: src/bar.c src/bar.h src/baz.h
?
I tried using the -MT flag, but it seems to discard object targets altogether.
-MT sets the entire target name.  If you want a different target for each source, you need a different -MT argument for each source, which means multiple invocations of the compiler and a foreach loop:
$(TARGET): build $(OBJECTS)
    $(CC) -shared -o $@ $(OBJECTS)
    rm autodep
    $(foreach SRC,$(SOURCES),$(CC) -MM -MT $(SRC:.c=.o) $(SRC) >> autodep;)
Alternately, you can use sed to massage the output
$(TARGET): build $(OBJECTS)
    $(CC) -shared -o $@ $(OBJECTS)
    $(CC) -MM $(SOURCES) | sed 's|^|src/|' > autodep
Easier still is to put the dependencies for each source file into it own .d file and use the -MMD flag to generate that when you compile the source file:
-include $(SOURCES:.c=.d)
CFLAGS += -MMD
$(TARGET): build $(OBJECTS)
    $(CC) -shared -o $@ $(OBJECTS)
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With