简体   繁体   中英

GCC makefile dependency generation path

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM