Question

What is the difference between these two targets:

%.o : %.cpp $(CXX) -c $(CXXFLAGS) $< -o $@

and

$(OBJ) : $(SRC) $(CXX) -c $(CXXFLAGS) $< -o $@

If we assume that SRC contains all the .cpp files present in the directory and OBJ = $(SRC:.cpp=.o)

Was it helpful?

Solution

The first specifies that each object file depends on its corresponding source file, and defines a reasonably sensible rule to make the object file ($@, the first target) from the source file ($^, all the dependencies). It should use $<, just the first dependency, since there will usually be other dependencies - headers included by the source file. You can often leave this rule out altogether; there's an implicit rule for compiling a single C++ file.

The second specifies that all the object files depend on all the source files, and defines a dysfunctional rule which will fail to compile anything. For example, defining SRC = a.cpp b.cpp, this expands to

g++ -c  a.cpp b.cpp -o a.o

which fails since -c only compiles a single source file:

g++: fatal error: cannot specify -o with -c, -S or -E with multiple files

OTHER TIPS

$(SRC) did NOT contain all source files! It contains a rule, how the source file name can be build from the object file name.

If $(SRC) contains all source files like a.c and b.c and $(OBJ) contains a.o and b.o the rule expands to:

a.o b.o: a.c b.c

which is not valid!

The difference:

$(OBJ) contains typically a list of needed object. So the rule knows which objects must be build. Make will call the compiler for all the source file and build the objects.

The first rule is only a rule which will actually do nothing without any other trigger for that.

If you complete your example to:

 %.o : %.cpp
    $(CXX) -c $(CXXFLAGS) $^ -o $@

do: x.o y.o
    $(CXX) -o do x.o y.o

make knows that x.o and y.o are needed for do. So he look for a rule to build them and catch your first rule.

But your first rule must not be defined manually, it normally exist already. For all implicit rules take a look at: https://www.gnu.org/software/make/manual/html_node/Catalogue-of-Rules.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top