I have this makefile:
CC=g++
CFLAGS=-c -Wall
all: hello
hello: main.o client.o
$(CC) main.o client.o -o hello
client.o: client.cpp client.h
$(CC) $(CFLAGS) client.cpp -o client.o
main.o: main.cpp
$(CC) $(CFLAGS) main.cpp -o main.o
clean:
rm -rf *o hello
Whenever I make changes in hello.h, client.o is rebuilt when I execute make. But when I try the resulting executable ./hello the change does not seem to happen.
The change is only reflected on ./hello if I add client.h to the main.o: rule like that
main.o: main.cpp client.h
$(CC) $(CFLAGS) main.cpp -o main.o
This will make things very difficult to maintain my code, any idea how to solve this problem?
Edit: tried this change:
main.o: main.cpp
$(CC) $(CFLAGS) -MD main.cpp -o main.o
but did not help.
UPDATE (final version):
TARGET = hello
CC = g++
CPPFLAGS = -Wall -MP -MD
LINKER = g++ -o
LFLAGS = -Wall
SRCDIR = src
OBJDIR = obj
BINDIR = bin
SOURCES := $(wildcard $(SRCDIR)/*.cpp)
INCLUDES := $(wildcard $(SRCDIR)/*.h)
OBJECTS := $(SOURCES:$(SRCDIR)/%.cpp=$(OBJDIR)/%.o)
DEPS := $(SOURCES:$(SRCDIR)/%.cpp=$(OBJDIR)/%.d)
RM = rm -rf
DIR_GUARD = mkdir -p $(@D)
$(BINDIR)/$(TARGET): $(OBJECTS)
@$(DIR_GUARD)
@$(LINKER) $@ $(LFLAGS) $(OBJECTS)
@echo "Linking complete!"
$(OBJECTS): $(OBJDIR)/%.o: $(SRCDIR)/%.cpp
@$(DIR_GUARD)
@$(CC) $(CPPFLAGS) -c $< -o $@
@echo "Compiled "$<" successfully!"
-include $(DEPS)
.PHONEY: clean
clean:
@$(RM) $(OBJDIR)/* $(BINDIR)/*
@echo "Cleanup complete!"
Thanks guys for all the help, you are truly amazing.