HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppModerate

makefile dependency generation

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
generationmakefiledependency

Problem

I need automatic dependency generation to be done in my makefile. So, I have tried to write one, after googling for similar ones. I have found some ways to do that, but the problem is that they are usually too complicated for me (because of usage of sed command etc. and I want a way for me to create a makefile without the need of refering to some other makefile).

Below is a makefile I hope should do the same job i.e. automatically find out all the dependencies of the object files and build them. Could you please review this makefile and point out cases where the build may fail when it should not have?

Gpp=g++
srcs=$(wildcard *.cpp)
objs=$(srcs:.cpp=.o)
deps=$(srcs:.cpp=.d)

default:test

%.o:%.d
    $(Gpp) -c $*.cpp

%.d:%.cpp
    echo -n "$*.d ">$*.d
    $(Gpp) -MM $*.cpp>>$*.d

test: $(objs)
    $(Gpp) $^ -o $@

-include $(deps)

.PHONY:clean default

clean:
    -rm -rf *.o test *.d


One place where the makefile fails is when for example a.cpp initially included a1.h but it has been updated to exclude a1.h and a1.h file has been deleted from file-system. So, except that is there any place that this makefile fails?

Solution

Not to be too blunt; but, you're going about this the wrong way. Look into the command line option -MMD for GCC, specify it when compiling your source; and, retain the inclusion statement for dependencies.

Also, no need for a default target. The first target is the default target.

An example:

Gpp = g++
srcs = $(wildcard *.cpp)
objs = $(srcs:.cpp=.o)
deps = $(srcs:.cpp=.d)

test: $(objs)
    $(Gpp) $^ -o $@

%.o: %.cpp
    $(Gpp) -MMD -MP -c %%CODEBLOCK_0%%lt; -o $@

.PHONY: clean

# $(RM) is rm -f by default
clean:
    $(RM) $(objs) $(deps) test

-include $(deps)

Code Snippets

Gpp = g++
srcs = $(wildcard *.cpp)
objs = $(srcs:.cpp=.o)
deps = $(srcs:.cpp=.d)

test: $(objs)
    $(Gpp) $^ -o $@

%.o: %.cpp
    $(Gpp) -MMD -MP -c $< -o $@

.PHONY: clean

# $(RM) is rm -f by default
clean:
    $(RM) $(objs) $(deps) test

-include $(deps)

Context

StackExchange Code Review Q#2547, answer score: 18

Revisions (0)

No revisions yet.