Your small C/C++ project has reached a point where it’s no longer practical to have all your code in one file. You want to split out a few components. So you make a src/ directory, and then… you have to write a real Makefile. Something more than hello: hello.o. Uh-oh… was it $@ or $< or $^? Crap. You don’t remember (I never do).
Do you have a ‘one-size fits all’ simple Makefile that can deal with straightforward source trees? If so, what’s in it and why? I’m looking for the smallest, simplest Makefile that can compile a directory full of C files nicely without me having to edit the Makefile every time I add a file. Here’s what I have so far:
CXX = clang++
CXXFLAGS = ...
LDFLAGS = ...
EXENAME = main
SRCS = $(wildcard src/*.cc)
OBJS = $(patsubst src%.cc,build%.o, $(SRCS))
all: $(EXENAME)
build/%.o: src/%.cc
@mkdir -p $(dir $@)
$(CXX) -c -o $@ $^ $(CXXFLAGS)
$(EXENAME): $(OBJS)
$(CXX) -o $@ $^ $(LDFLAGS)
clean:
rm -rf $(EXENAME) build/
This Makefile builds all the .cc files in the src/ directory into .o files in the build/ directory, then links them up into the parent directory.
What would you do differently?
I would reconsider you decision not to have an explicit list of sources– I think it may cause you trouble in the long run. But if that’s your decision, this makefile is pretty good.
In the
%.orule I would use$<instead of$^, so that later you can add dependencies likeAnd when you’re ready, you can take a look at Advanced Auto-Dependency Generation.