Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GCC makefile dependency generation path

Tags:

gcc

makefile

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.

like image 968
Avidan Borisov Avatar asked Mar 14 '13 21:03

Avidan Borisov


1 Answers

-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)
like image 178
Chris Dodd Avatar answered Oct 08 '22 18:10

Chris Dodd