1
votes

I am making a makefile which compiles a program located in multiple directories. All of the source files are in /src, the headers are in /inc, the object files will be created in /obj, and the executable will be created in /bin. There are three makefiles, an overall one, one in the /obj directory and one in the /bin directory. The obj makefile creates the object files and the bin makefile links the files creating an executable. I am not supposed to hard-code values as this makefile needs to be as generic as possible, this includes hard coding file and directory names.

The code below is the makefile that creates the object files. It creates the object files but won't properly check dependencies so when I update one file, it will recreate all the object files. I've been reading through the GNU Makefile Manual but still don't understand what is going wrong.

CC:= gcc
CCFLAGS:= -MMD -g -Wall
INCLUDE:= -I "../inc"
LDFLAGS:= -lcurses -lgdbm -lncurses -lgdbm_compat
SRC:= ../src

SOURCES:= $(wildcard $(SRC)/*.c)
OBJS:=$(patsubst $(SRC)/%.c,%.o,$(SOURCES))

all: $(OBJS)

$(OBJS): $(SOURCES)
    $(CC) $(CCFLAGS) $(INCLUDE) -c $^

VPATH= ../$(PROG)
$(SOURCES): 
    $(CC) $(CC_FLAGS) $(INCLUDE) -c $<

.PHONY: clean

clean:
    rm -f *.[od]  *.o

-include *.d

I can post the other two makefiles if needed.

1
Are you sure you want multiple makefiles?Beta
It is a requirement to have one top level makefile, one to create the object files, and one to link them. All of which are located in different foldersKat

1 Answers

2
votes

In yous $(OBJS) rule, each object file depends on all source files, so when you modify one source file, Make rebuilds all of the objects. Try this:

$(OBJS): %.o : $(SRC)/%.c
    $(CC) $(CCFLAGS) $(INCLUDE) -c $<