sps
sps

Reputation: 2720

Makefile | Dependency on another Header file included in Header file

Suppose I have below rule in Makefile.

test.o: test.cpp foo.h
        g++ -c -o test.o test.cpp

Now suppose foo.h includes bar.h as seen below.

user $ head -n 5 foo.h
#include"bar.h"
/*
.
.
*/
user $  

Will the test.o be built again if there are any changes in bar.h ?

Or should I specifically mention bar.h in the rule as below:

test.o: test.cpp foo.h bar.h
        g++ -c -o test.o test.cpp

Upvotes: 4

Views: 2515

Answers (2)

DevSolar
DevSolar

Reputation: 70263

Will the test.o be built again if there are any changes in bar.h?

No. Make has no way of knowing about this dependency, or checking for changes in your #includes.

Except, of course, if you leave handling header dependencies to the entity who knows about them: The compiler. (Assuming GCC and GNU make in this example.)

  1. Don't list headers as dependencies at all.

  2. Generate a list of source files in your project.

    SRCFILES := ...
    
  3. Generate a list of dependency files, one .d file for each SRCFILE.

    DEPFILES := $(patsubst %.cpp,%.d,$(SRCFILES))
    
  4. Include those dependency files into your Makefile. (The leading - means Make will not generate an error if they don't exist, e.g. on first compilation.)

    -include $(DEPFILES)
    
  5. Using a generic rule, let the compiler generate a list of the header dependencies during compilation of each source file.

    %.o: %.cpp Makefile
        @$(CXX) $(CXXFLAGS) -MMD -MP -c $< -o $@
    

    -MMD generates Make rules making the object files depend on any (non-system) header files included, named *.d. -MP adds dummy rules that avoid errors should a header file be removed from your sources.

Upvotes: 6

YSC
YSC

Reputation: 40070

GCC (and probably Clang) can build a list of dependencies for you; This way, you can simply make your object files from their source (cpp) file:

depend: .depend

.depend: $(SRC_FILES)
        rm -f ./.depend
        $(CC) $(CFLAGS) -MM $^ -MF  ./.depend;

include .depend

%.o: %.cpp
    $(CC) $(CFLAGS) -c $<

You might also find interest in the makedepend tool.

Upvotes: 3

Related Questions