Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Makefile | Dependency on another Header file included in Header file

Tags:

c++

makefile

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
like image 292
sps Avatar asked Jan 07 '23 00:01

sps


1 Answers

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.

like image 198
DevSolar Avatar answered Jan 22 '23 12:01

DevSolar