1

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.

Ghooo
  • 496
  • 1
  • 3
  • 11

1 Answers1

1

The problem is that the dependency of main.o on client.h is not specified in your Makefile. Use:

main.o: main.cpp client.h
        $(CC) $(CFLAGS) main.cpp -o main.o
R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • this will make my code very hard to maintain, as adding any new class will require that, is there another way of specifying that without changing the main.o ? – Ghooo Aug 31 '15 at 17:33
  • 1
    @Ghooo, If you are using gcc/g++, lookup the options `-MMD` and `-MD`. – R Sahu Aug 31 '15 at 17:38
  • 3
    Also see [Auto-Dependency Generation](http://make.mad-scientist.net/autodep.html). – Etan Reisner Aug 31 '15 at 17:45
  • the answer to this [question](http://stackoverflow.com/questions/8025766/makefile-auto-dependency-generation) was really helpful. – Ghooo Sep 02 '15 at 00:52