1

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}
asked Jul 16, 2010 at 9:05
1
  • This is tricky. I'd wait for a profi response. The crux of the problem (obviously) that .d depends only on the .cpp, and ignores the header file changes. So in a way, .d has to depend on .d .... Dependencies is one of the reasons why I do not use make for everything. Commented Jul 16, 2010 at 10:57

2 Answers 2

2

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

answered May 23, 2011 at 6:00
Sign up to request clarification or add additional context in comments.

Comments

1

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.

answered Jul 16, 2010 at 11:20

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.