Brian Hooper
Brian Hooper

Reputation: 22034

Makefile dependency generation not checking headers

I'm using a makefile intending to generate dependencies automatically. But with my file, I find that although changes to the header files cause the code to be recompiled, they don't cause the dependencies to be regenerated, as I think they ought. Can anyone see what I have missed out?

.SUFFIXES : .hpp .cpp .d .o
SOURCES=main.cpp sub1.cpp sub2.cpp
OBJECTS=${SOURCES:.cpp=.o}
DEPENDENCIES=${SOURCES:.cpp=.d}

.cpp.d:
    g++ -MM $< > $@
.cpp.o:
    g++ $< -c `pkg-config gtkmm-2.4 --cflags --libs` -g

calculator: ${OBJECTS} ${DEPENDENCIES}
    g++ ${OBJECTS} -o calculator `pkg-config gtkmm-2.4 --cflags --libs` -g

include ${DEPENDENCIES}

Upvotes: 1

Views: 1559

Answers (2)

user760613
user760613

Reputation:

While I agree with Dummy00001's solution, it might help to add a -MP flag to g++ command to generate the dependency files. What it does is it adds PHONY targets with the names of all the header files in the dependency list.

i.e. if g++ -MM $< generates

test.o: test.cpp test.h dummy.h etc_bkp.h

then g++ -MM -MP $< generates

test.o: test.cpp test.h dummy.h etc_bkp.h
test.h:
dummy.h:
etc_bkp.h:

this would help the make not to break even if a renaming is done or a file has been deleted

Upvotes: 2

Dummy00001
Dummy00001

Reputation: 17420

Found solution myself. The trick also appears in the official GNU make documentation.

The line to generate the dependencies should look like that:

.cpp.d:
        g++ -MM $< | sed 's!^$(<:.cpp=.o):!$(<:.cpp=.o) $(<:.cpp=.d):!' > $@

The sed translates the dependency line from "main.o: main.cpp include/hello.hpp" into "main.o main.d: main.cpp include/hello.hpp" (example from my minimized test) thus making .d depend on the same files as the .o file itself.

Though I personally recommend to use e.g. SCons which is capable of automatic dependency tracking, as (in my experience) the GNU make solution breaks often when a new header file is introduced or some files were renamed.

Upvotes: 1

Related Questions