0

How can I setup a Makefile so it only compiles the source files that actually includes the .h file that changed instead of compiling every file?

lets say I have following variables for my source files and include files:

SRC := SRC/*.c
OBJ := $(SRC:.c=.o)

INC := INC/*.h

TARGET := programm 

Now I have following rules to create the TARGET:

$(TARGET) : $(OBJ) $(INC)
    $(CC) $(CFLAGS) $(OBJ) -o $@
#CC is the compiler and CFLAGS the flags to compile e.g. gcc -Wall -Werror

Bu if I change something in of the INC files it will recompile all object files. Is there a way to have the makefile just compile the files that actually are effected by the change in the .h file?

Alan Birtles
  • 32,622
  • 4
  • 31
  • 60
jsiller
  • 78
  • 7
  • 3
    after removing `$(INC)` from your dependencies follow the duplicate to setup the dependencies properly – Alan Birtles Mar 17 '22 at 09:34
  • With `$(TARGET) : $(OBJ) $(INC)` and `$INC` expanding to _all_ .h files, you're literally telling make that the target depends on all .h file. So if you change a single .h file the target will be rebuilt. – Jabberwocky Mar 17 '22 at 09:37
  • 1
    Depending on your compiler toolchain, you should be able to configure per-target [*automatic* dependencies](https://www.gnu.org/software/make/manual/html_node/Automatic-Prerequisites.html) on headers. both clang and gcc absolutely support this in one form or another. I suspect that is what you're really after. – WhozCraig Mar 17 '22 at 09:42

0 Answers0