4

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

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

Your Answer

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.