views:

3989

answers:

4

I have a project that has a makefile with broken dependencies. Is there any best known way to generate a list of dependencies for the project that I can use in the makefile, other than examining each source file by hand or with a hand written perl script?

+2  A: 

The GNU C preprocessor cpp has an option, -MM, which produces a make-suitable set of dependencies based on inclusion patterns.

Barry Kelly
+2  A: 

MakeDepend is probably what you need.

MakeDepend is deprecated in favor of the dependency generation built into the compilers themselves, since there is/can be differences in the file depending upon how they process the preprocessor macros. (ie #ifdef G++#include "gpp.h"#endif
Stefan Mai
+8  A: 

http://make.paulandlesley.org/autodep.html has a good solution.

Absolutely. g++ -MM will generate a GMake compatible list of dependencies. I use something like this:

# Add .d to Make's recognized suffixes.
SUFFIXES += .d

#We don't need to clean up when we're making these targets
NODEPS:=clean tags svn
#Find all the C++ files in the src/ directory
SOURCES:=$(shell find src/ -name "*.cpp")
#These are the dependency files, which make will clean up after it creates them
DEPFILES:=$(patsubst %.cpp,%.d,$(SOURCES))

#Don't create dependencies when we're cleaning, for instance
ifeq (0, $(words $(findstring $(MAKECMDGOALS), $(NODEPS))))
    #Chances are, these files don't exist.  GMake will create them and
    #clean up automatically afterwards
    -include $(DEPFILES)
endif

#This is the rule for creating the dependency files
src/%.d: src/%.cpp
    $(CXX) $(CXXFLAGS) -MM -MT '$(patsubst src/%,obj/%,$(patsubst %.cpp,%.o,$<))' $< > $@

#This rule does the compilation
obj/%.o: src/%.cpp src/%.d src/%.h
    @$(MKDIR) $(dir $@)
$(CXX) $(CXXFLAGS) -o $@ -c $<

What this will do is automatically generate the dependencies for each file that has changed, and compile them according to whatever rules you have in place. This allows me to just dump new files into the src/ directory, and have them compiled in automatically dependencies and all.

Stefan Mai
Don't fall into this trap if you have more than 100 files, because it's too slow the first time. In this case, you should use something that is invoked once, not once for each file. Makedepend might have this option. At work, we use a custom perl script.
Steve Hanov
Thanks, I'll keep that in mind. My current project has about a dozen files, so it doesn't have big overhead. Besides, the initial build takes more than 20 minutes, so I always run that, go get some coffee, and run incremental builds after that.
Nathan Fellman
A: 

The Digital Mars C/C++ compiler comes with a makedep tool.

Walter Bright
what platforms is this available for?
Nathan Fellman