[Gcc] How can I have a Makefile automatically rebuild source files that include a modified header file? (In C/C++)
You could add a 'make depend' command as others have stated but why not get gcc to create dependencies and compile at the same time:
DEPS := $(COBJS:.o=.d) -include $(DEPS) %.o: %.c $(CC) -c $(CFLAGS) -MM -MF $(patsubst %.o,%.d,$@) -o $@ $<
The '-MF' parameter specifies a file to store the dependencies in.
The dash at the start of '-include' tells Make to continue when the .d file doesn't exist (e.g. on first compilation).
Note there seems to be a bug in gcc regarding the -o option. If you set the object filename to say
obj/_file__c.o then the generated
_file_.d will still contain
I have the following makefile that I use to build a program (a kernel, actually) that I'm working on. Its from scratch and I'm learning about the process, so its not perfect, but I think its powerful enough at this point for my level of experience writing makefiles.
AS = nasm CC = gcc LD = ld TARGET = core BUILD = build SOURCES = source INCLUDE = include ASM = assembly VPATH = $(SOURCES) CFLAGS = -Wall -O -fstrength-reduce -fomit-frame-pointer -finline-functions \ -nostdinc -fno-builtin -I $(INCLUDE) ASFLAGS = -f elf #CFILES = core.c consoleio.c system.c CFILES = $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.c))) SFILES = assembly/start.asm SOBJS = $(SFILES:.asm=.o) COBJS = $(CFILES:.c=.o) OBJS = $(SOBJS) $(COBJS) build : $(TARGET).img $(TARGET).img : $(TARGET).elf c:/python26/python.exe concat.py stage1 stage2 pad.bin core.elf floppy.img $(TARGET).elf : $(OBJS) $(LD) -T link.ld -o $@ $^ $(SOBJS) : $(SFILES) $(AS) $(ASFLAGS) $< -o $@ %.o: %.c @echo Compiling $<... $(CC) $(CFLAGS) -c -o $@ $< #Clean Script - Should clear out all .o files everywhere and all that. clean: -del *.img -del *.o -del assembly\*.o -del core.elf
My main issue with this makefile is that when I modify a header file that one or more C files include, the C files aren't rebuilt. I can fix this quite easily by having all of my header files be dependencies for all of my C files, but that would effectively cause a complete rebuild of the project any time I changed/added a header file, which would not be very graceful.
What I want is for only the C files that include the header file I change to be rebuilt, and for the entire project to be linked again. I can do the linking by causing all header files to be dependencies of the target, but I cannot figure out how to make the C files be invalidated when their included header files are newer.
I've heard that GCC has some commands to make this possible (so the makefile can somehow figure out which files need to be rebuilt) but I can't for the life of me find an actual implementation example to look at. Can someone post a solution that will enable this behavior in a makefile?
EDIT: I should clarify, I'm familiar with the concept of putting the individual targets in and having each target.o require the header files. That requires me to be editing the makefile every time I include a header file somewhere, which is a bit of a pain. I'm looking for a solution that can derive the header file dependencies on its own, which I'm fairly certain I've seen in other projects.
If you are using a GNU compiler, the compiler can assemble a list of dependencies for you. Makefile fragment:
depend: .depend .depend: $(SOURCES) rm -f ./.depend $(CC) $(CFLAGS) -MM $^>>./.depend; include .depend
There is also the tool
makedepend, but I never liked it as much as
How can I have a Makefile automatically rebuild source files that include a modified header file? (In C/C++)
As already pointed out elsewhere on this site, see this page: http://make.paulandlesley.org/autodep.html
In short, gcc can automatically create .d dependency files for you, which are mini makefile fragments containing the dependencies of the .c file you compiled. Every time you change the .c file and compile it, the .d file will be updated.
Besides adding the -M flag to gcc, you'll need to include the .d files in the makefile (like Chris wrote above). There are some more complicated issues in the page which are solved using sed, but you can ignore them and do a "make clean" to clear away the .d files whenever make complains about not being able to build a header file that no longer exists.
Most answers are surprisingly complicated or erroneous. However simple and robust examples have been posted elsewhere [codereview]. Admittedly the options provided by the gnu preprocessor are a bit confusing. However, the removal of all directories from the build target with
-MM is documented and not a bug [gpp]:
By default CPP takes the name of the main input file, deletes any directory components and any file suffix such as ‘.c’, and appends the platform's usual object suffix.
The (somewhat newer)
-MMD option is probably what you want. For completeness an example of a makefile that supports multiple src dirs and build dirs with some comments. For a simple version without build dirs see [codereview].
CXX = clang++ CXX_FLAGS = -Wfatal-errors -Wall -Wextra -Wpedantic -Wconversion -Wshadow # Final binary BIN = mybin # Put all auto generated stuff to this build dir. BUILD_DIR = ./build # List of all .cpp source files. CPP = main.cpp $(wildcard dir1/*.cpp) $(wildcard dir2/*.cpp) # All .o files go to build dir. OBJ = $(CPP:%.cpp=$(BUILD_DIR)/%.o) # Gcc/Clang will create these .d files containing dependencies. DEP = $(OBJ:%.o=%.d) # Default target named after the binary. $(BIN) : $(BUILD_DIR)/$(BIN) # Actual target of the binary - depends on all .o files. $(BUILD_DIR)/$(BIN) : $(OBJ) # Create build directories - same structure as sources. mkdir -p $(@D) # Just link all the object files. $(CXX) $(CXX_FLAGS) $^ -o $@ # Include all .d files -include $(DEP) # Build target for every single object file. # The potential dependency on header files is covered # by calling `-include $(DEP)`. $(BUILD_DIR)/%.o : %.cpp mkdir -p $(@D) # The -MMD flags additionaly creates a .d file with # the same name as the .o file. $(CXX) $(CXX_FLAGS) -MMD -c $< -o $@ .PHONY : clean clean : # This should remove all generated files. -rm $(BUILD_DIR)/$(BIN) $(OBJ) $(DEP)
This method works because if there are multiple dependency lines for a single target, the dependencies are simply joined, e.g.:
a.o: a.h a.o: a.c ./cmd
is equivalent to:
a.o: a.c a.h ./cmd
as mentioned at: Makefile multiple dependency lines for a single target?
Easy makefiles for gcc/g++
How about this:
%.o: %.cpp %.h $(CC) -c $< -o $@ # Some things have extra dependencies. (Headers like util.h are unlikely # to change, but you can handle them this way if you really want to.) # # foo.o and bar.o both depend on baz.h foo.o bar.o: baz.h # foo.o also depends on gab.h and jig.h foo.o: gab.h jig.h # You will need a list of object files. You can build it by hand: OBJ_FILES = foo.o bar.o snaz.o # and so on # ...or just grab all the files in the source directory: SOURCE_FILES = $(wildcard *.cpp) OBJ_FILES = $(SOURCE_FILES:.cpp=.o) # It is possible to get this from the environment, but not advisable. LIBS = -lred -lblue final-thing: $(OBJ_FILES) $(CC) $(LIBS) $^ -o $@
Perhaps you can check out CMake?
If you're unfamiliar with CMake, it's basically a Makefile generator (or XCode, or Visual Studio Projects, etc, depending on platform), so it lets you specify just the variables you need, and takes care of header dependency issues for you, makefile generation, etc.