Skip to content
Advertisement

What does `OBJECTS = $(SOURCES:.cpp=.o)` mean in a makefile

I am going over this tutorial and it has something like this

# File names
EXEC = run
SOURCES = $(wildcard *.cpp)
OBJECTS = $(SOURCES:.cpp=.o)    

.....
%.o: $(SRCPATH)/%.cpp $(INC)
    $(CC) $(CXXFLAGS) $(INCLUDES) -c $< -o $@

I am not sure if I understand the document and would appreciate it if someone could explain the last two statements. Here are my three questions regarding Makefile

Question 1 :

Whats the difference between

 SOURCES = $(wildcard *.cpp)

and

 SOURCES = $(*.cpp)

It says that the second case only works if .cpp files exist since they do not therefore it wont work. My question is why does the first one work ?

Question 2: What does the 'wildcard *' mean ? what does the last statement OBJECTS = $(SOURCES:.cpp=.o) mean ?

Question 3: What does %.o mean when it is placed as a target ? Whats the difference between *.o , %.o and wildcard *.cpp

Advertisement

Answer

SOURCES = $(*.cpp)
SOURCES = *.cpp
SOURCES = $(wildcard *.cpp)

The first one is an error, the second expands too late (not on definition), the third searches for all files with suffix .cpp in the source directories.
The builtin-function wildcard is used to force wildcard-expansion where it does not naturally occur.

OBJECTS = $(SOURCES:.cpp=.o)

That means OBJECTS is assigned the value of SOURCES, after substituting every .cpp at the end of an item with .o.

And %.o as a target means you are defining a rule for creating .os from something else.

References: GNU make manual

See here for a good basic makefile: https://stackoverflow.com/a/26579143

Advertisement