My makefile contains the following lines
11 SRC := $(shell echo src/*.cpp)
12 SRC += $(shell echo $(TEST_ROOT)/*.cpp)
13
14 OBJECTS = $(SRC:.cpp=.o)
22 # [debug] target
23 $(TARGET): $(OBJECTS)
24 $(CC) $(OBJECTS) -o $(TARGET)
25
26 # [debug] .o
27 $(OBJECTS): $(SRC)
28 $(CC) $(CFLAGS) $(DEBUG_FLAGS) -c $(SRC) $(OBJECTS)
Which fails because … well the following evidently is not a way to do it
g++ -pedantic -Wall -Werror -O0 -g -Wno-format -DUSE_MEASURE -c src/Timer.cpp test/TimerTest.cpp src/Timer.o test/TimerTest.o
How should i modify line #28 to produce .o from all my sources please?
This should do the trick:
This rule will build one object file, and Make will call it once for each object that the other rule needs. You can write a rule that will build all object files in one pass, but there’s no advantage to that.
EDIT:
Suppose
SRCissrc/foo.cpp src/bar.cpp testroot/baz.cpp,so
OBJECTSissrc/foo.o src/bar.o testroot/baz.oWe could have a separate rule for each:
But that’s redundant (since the commands are very similar) and inconvenient (since we don’t want to add/remove rules whenever we add/remove targets). So we use a pattern rule:
Now when Make wants to build
src/foo.o, it sees that the target matches the pattern%.o, the stem (corresponding to%) issrc/foo, and the corresponding prereq,src/foo.cppexists, so it uses this rule.But we have a variable
OBJECTSthat lists the targets we want to build with this rule, so we can restrict it to a static pattern rule, which looks about the same but has some advantages we need not get into here:Now for the
...part. The command tells the compiler to scan the prereq (src/foo.cpp) and build the target (src/foo.o), so we must refer to those things in the command. Automatic variables help with that;$@is the name of the target, and$<is the name of the first (and in this case the only) prerequisite: