Reputation: 254
I am trying to write a makefile that can create one executable per main function.
I have a list of files: main1.cpp
, main2.cpp
, and main3.cpp
. They each contain an int main()
function. Obviously I can't build these into one exec, which is not the goal here, so how can I build each one of these into its own executable? This is one solution:
main1: main1.cpp
$(CC) -o $@ $^
main2: main2.cpp
$(CC) -o $@ $^
main3: main3.cpp
$(CC) -o $@ $^
But there MUST be a better way to do this. Is there some type of looping feature to makefiles that will make this process easier? Like a for loop?
Upvotes: 0
Views: 391
Reputation: 29345
A mixture of wildcard
, patsubst
and static pattern rules, plus the standard make variables for C++ compilation and linking:
SRCS := $(wildcard main*.cpp)
EXES := $(patsubst %.cpp,%,$(SRCS))
$(EXES): %: %.cpp
$(CXX) $(CXXFLAGS) $(LDFLAGS) -o $@ $< $(LDLIBS)
But as make knows already how to make all this you could as well get rid of your Makefile and just type make main1
...
Upvotes: 2
Reputation: 104589
While it's not a very sophisticated makefile, your solution is fine for three simple programs. You could make it more generic and support building all three targets at the same time with an "all" target.
all: main1 main2 main3
main1: main1.cpp
$(CC) -o $@ $^
main2: main2.cpp
$(CC) -o $@ $^
main3: main3.cpp
$(CC) -o $@ $^
Upvotes: 0