0

I have a project with several folders:

Project |_ include/ | '- Eigen/ |_ obj/ |_ src/ |_ makefile

All .cpp files are in src/ and have dependencies with several .hpp files in include/ and with the Eigen library too.

Now, everytime I edit a source file I can use the make command, however when I change a header file it tells me that all is up to date.

I've tried several examples that I found on similar questions and I've read some tutorials on makefiles but I cannot manage to make it work properly.

Also every time it compiles, if a .cpp that uses the Eigen library was modified, it takes very very very long, like it is reading again through all Eigen headers.

My makefile:

CC := g++
SRCDIR := src
OBJDIR := obj
TARGET := main

JPEG_LIB_DIR = /usr/local/lib

SRCEXT := cpp
SOURCES := $(shell find $(SRCDIR) -name *.$(SRCEXT))
OBJECTS := $(SOURCES:$(SRCDIR)/%.$(SRCEXT)=$(OBJDIR)/%.o)

CFLAGS := -W -Wall -g -rdynamic -std=c++11
LIB += -pthread
LIB += -ljpeg 
LFLAGS += -L$(JPEG_LIB_DIR)
INC += -I include

.PHONY: clean

all: $(TARGET)

$(TARGET): $(OBJECTS)
    $(CC) $(LFLAGS) $^ $(LIB) -o $@

$(OBJDIR)/%.o: $(SRCDIR)/%.$(SRCEXT)
    @mkdir -p $(OBJDIR)
    $(CC) $(INC) $(CFLAGS) -o $@ -c $<

clean:
    $(RM) -r $(OBJDIR) $(TARGET)

(I've tried this and that but it won't even compile).

Thank you!

SarahHime
  • 43
  • 4
  • 1
    You didn't add any dependencies for header files, so why should `make` decide to recompile your source files? – user0042 Jul 12 '17 at 18:02

2 Answers2

0

You have to explicitly tell make that your targets depend on the header files.

There are many automated ways to do this, but you can also simply just add the header files to your SOURCES list (which right now only contains .cpp files).

architrex
  • 171
  • 1
  • 7
  • That will not work, Make will not rebuild the object files, it will simply rebuild the executable using the old object files, which will change nothing. – Beta Jul 13 '17 at 00:46
0

The simplest way is to make all header files prerequisites of each object file:

INCDIR := include
HEADERS := $(notdir $(wildcard $(INCDIR)/*.h))

$(OBJDIR)/%.o: $(SRCDIR)/%.$(SRCEXT) $(HEADERS)
    ...

This is crude but effective. It will cause Make to recompile all object files whenever any header file has been changed. This is overkill, and there are more subtle methods that avoid all of that unnecessary work, but you must understand this much before you attempt them.

Beta
  • 96,650
  • 16
  • 149
  • 150