Search code examples
c++makefiledependenciesobject-files

Managing Dependency Complexity in Make Files


I am working on my first open source C++ project: https://github.com/jehugaleahsa/spider-cpp.

I am managing my own Makefile and I have "best practices" question regarding how to manage dependencies. Right now, I make each .o file dependent on each of the included header files in the .cpp file. So:

code.o: code.cpp code.hpp dep1.hpp de2.hpp
    g++ -c code.cpp

First of all, I am pretty sure Make supports a shorthand for creating object files. If someone would show an example of this, I'd appreciate it.

Next, is there a way to avoid listing every included header as a dependency? I want to make sure if I change a dependency, that the changes are still compatible. Listing the included headers is tedious and easy to mess up.


Solution

  • OP:

    First of all, I am pretty sure Make supports a shorthand for creating object files. If someone would show an example of this, I'd appreciate it.

    From here:

    OBJS := foo.o bar.o
    
    #Your program should have the objects as dependencies, and link them
    proggie: $(OBJS)
    gcc $(OBJS) -o proggie
    
    
    # compile
    %.o: %.c
        gcc -c $(CFLAGS) $*.c -o $*.o
    

    OP:

    Next, is there a way to avoid listing every included header as a dependency

    Lower down on the same page, see these lines:

    # pull in dependency info for *existing* .o files
    -include $(OBJS:.o=.d)
    
    
    # compile and generate dependency info
    %.o: %.c
        gcc -c $(CFLAGS) $*.c -o $*.o
        gcc -MM $(CFLAGS) $*.c > $*.d
    

    Basically what this does is use gcc's -MM option to obtain a list of header files, and now we can depend on them. Thus we output a file with a list of such header files to a .d file, and then next time, we add the list of files as a dependency, which is what the -include command does. The "-" avoids error if the dependency .d files don't exist yet.

    Note, you should modify the above to account for .cpp files