GCC makefile dependency generation path

I use the flag -MMin GCC to create makefile dependencies for objects. A macro file looks something like this:

-include autodep
...
$(TARGET): build $(OBJECTS)
    $(CC) -shared -o $@ $(OBJECTS)
    $(CC) -MM $(SOURCES) > autodep

Sources are located in the folder src. However, the file autodepwill contain target objects without their relative path:

foo.o: src/foo.c src/foo.h
bar.o: src/bar.c src/bar.h src/baz.h

How can I include them in this:

src/foo.o: src/foo.c src/foo.h
src/bar.o: src/bar.c src/bar.h src/baz.h

?

I tried to use a flag -MT, but it seems to completely throw away the targets of the object.

+5
source share
1 answer

-MTsets the full name of the target. If each source requires a different goal, each source needs a different argument -MT, which means multiple calls to the compiler and foreach loop:

$(TARGET): build $(OBJECTS)
    $(CC) -shared -o $@ $(OBJECTS)
    rm autodep
    $(foreach SRC,$(SOURCES),$(CC) -MM -MT $(SRC:.c=.o) $(SRC) >> autodep;)

Alternatively, you can use sed to massage output

$(TARGET): build $(OBJECTS)
    $(CC) -shared -o $@ $(OBJECTS)
    $(CC) -MM $(SOURCES) | sed 's|^|src/|' > autodep

.d -MMD, :

-include $(SOURCES:.c=.d)
CFLAGS += -MMD

$(TARGET): build $(OBJECTS)
    $(CC) -shared -o $@ $(OBJECTS)
+6

All Articles