Question

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.

Was it helpful?

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

OTHER TIPS

Yes, make supports shorthand for creating object files. This is called rules. And yes, there is a way to avoid listing every included header as a dependency. g++/gcc has -MM option which will generate the full list of dependencies.

Unfortunately, there is no simple explanation on how to do it which I could put here.. You have to read docs and play with make utility. I found this book very helpful: "Managing Projects with GNU Make". There is a doc on GNU site but I found it a bit harder to read. www.gnu.org/software/make/manual/make.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top