I've been following a few tutorials to create Makefiles and came across one at http://www.cs.colby.edu/maxwell/courses/tutorials/maketutor/ which I managed to get working across some simple functions and programs:

IDIR = include


_DEPS = hellomake.hpp
DEPS = $(patsubst %,$(IDIR)/%,$(_DEPS))

_OBJ = hellomake.o hellofunc.o 
OBJ = $(patsubst %,$(ODIR)/%,$(_OBJ))

$(ODIR)/%.o: %.cpp $(DEPS)
	$(CC) -c -o $@ $< $(CFLAGS)

hellomake: $(OBJ)
	$(CC) -o $@ $^ $(CFLAGS)

.PHONY: clean

	rm -f $(ODIR)/*.o *~ core $(INCDIR)/*~

My question is this: is there a way for a Makefile to automatically generate _DEPS and _OBJ in the above example by scanning the contents of include and src respectively? e.g. _DEPS = function(contents of include), _OBJ = function(contents of src (not main.cpp ) with .cpp replaced by .o). I read somewhere about using

OBJ = $(SRC:.cpp = .o)

to generate a list with the same name but different filetype but am temporarily stuck.

Thanks in advance for any help/tips/pointers

The way you set it up is suboptimal. Usually each object file has its own list of dependencies; having just one _DEPS for everyting leads to excessive recompilation. A typical solution uses g++ for dependency generation:

# Each .cpp will have its own .d, and the list of a dependency files is created from the list of sources:
DEPS = $(SRC:.cpp = .d)

# Same story with objects:
OBJS = $(SRC:.cpp = .o)

# A generic rule to generate a dependency (.d) file from a given .cpp:
%.d: %.cpp
    $(CXX) $(CFLAGS) -MM $< -o $@

# The generated dependency file is in fact a makefile fragment; include them all in the master makedile:
-include $(DEPS)

Because make software comes in many flavors and the script it executes 'can' depend on the operating system...It really depends.

This article has been dead for over six months. Start a new discussion instead.