Makefile dependencies

So I inherited a project that apparently had Makefiles written by people who had no idea how Makefiles are supposed to work.

When I edited one of the header files and reran make, nothing happened. So I read some stuff online about making gcc auto-create dependency files. However, they seemed to be outdated pages that referred to using sed and stuff when gcc seems to automagically dump the proper format already. And this is a RHEL3 box, so not exactly cutting edge.

Anyway, I went with a hybrid approach of a few different pages I found, so figured I would share it here.

These reply on the "main" Makefiles defining OBJS as the target files (.o, e.g. SocketHandler.o).

In the main Makefile, I redefined their CLEAN_CMD to add $(OBJS:.o=.d) to the $(RM) command. Then, after the OBJS was defined, I include Makefile.dep.

Also note that this is a little convoluted because the project actually combines a bunch of .o files into .a library files. For non-library compilations, the targets would just be %o and the gcc command line would be slightly tweaked. I just wanted to show the newer-than-any-webpage-I-saw -MF command. No more sed or redirects needed.


# This Makefile will generate .d files for every source file found.
# This allows make to handle header files properly.

# This file must be included AFTER $OBJS has been defined, not in
# the global Makefile

# Include existing .d if they are present:
-include $(OBJS:.o=.d)

# Override default cpp and c compiling instructions:
$%(%.o) : %.c 
        $(CC) -MM -MP $(CPPFLAGS) $(CFLAGS) $*.c -MT "$@($*.o)" -MF $*.d
        $(CC) -c $(CPPFLAGS) $(CFLAGS) $*.c -o $*.o
        $(AR) cr $@ $*.o

$%(%.o) : %.cpp
        $(CXX) -MM -MP $(CPPFLAGS) $(CXXFLAGS) $*.cpp -MT "$@($*.o)" -MF $*.d
        $(CXX) -c $(CPPFLAGS) $(CXXFLAGS) $*.cpp -o $*.o
        $(AR) cr $@ $*.o


No comments.