Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 417
MistyD Avatar asked Jan 09 '23 13:01

MistyD


2 Answers

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

like image 98
Deduplicator Avatar answered Jan 12 '23 02:01

Deduplicator


All of your questions are answerable via a reading of the GNU Make Manual.

The section on wildcards in the GNU Make Manual is worth reading for what I believe the author of that page was trying to explain about not using *.cpp as it may not do what you want. (The authors point about make ignoring modification times because of the bare glob is, however, entirely incorrect.)

That section continues into the section on the wildcard function. Which is just a make-expanded globbing function to control time of expansion (variable definition time instead of variable use time).

$(SOURCES:.cpp=.o) is a Substitution Reference.

%.o as a target is a Pattern Rule.

*.o is a glob.

$(wildcard *.cpp) (not wildcard *.cpp) was covered earlier.

like image 34
Etan Reisner Avatar answered Jan 12 '23 03:01

Etan Reisner