I have my object files compiled into a specific location using these variables and targets:
OBJDIR=./obj
objdir:
$(MKDIR) $(OBJDIR)
%.o: %.cpp objdir
$(CXX) $(CXXFLAGS) -c $< -o $(OBJDIR)/$@
Now my problem is, when it comes to linking the executable, I want to use variables to hold the lists of object files, such as:
FOOOBJECTS=foo.o foo1.o foo2.o
BAROBJECTS=bar.o bar1.o
mycrappyprogram: main.o $(FOOBOJECTS) $(BARBOJECTS)
$(CXX) $(FOOBJECTS) $(BAROBJECTS) -o $(BINDIR)/mycrappyprogram
Of course I can't do this because all the objects are in ./obj/ so the recipe can't find them.
How can I define a list of object files once, and have them be qualified when used in the recipe?
1) Make can manipulate strings:
FOOOBJECTS=foo.o foo1.o foo2.o
BAROBJECTS=bar.o bar1.o
OBJECTS = $(addprefix $(OBJDIR)/, $(FOOOBJECTS) $(BAROBJECTS))
2) Automatic variables are your friends (and I presume you want your executable to incorporate main.o, and not just the foo and bar objects):
mycrappyprogram: main.o $(OBJECTS)
$(CXX) $^ -o $(BINDIR)/$@
3) A (non-PHONY) rule should build the very thing it says it will build, or you'll get into trouble:
$(BINDIR)/mycrappyprogram: main.o $(OBJECTS)
$(CXX) $^ -o $@
$(OBJDIR)/%.o: %.cpp objdir
$(CXX) $(CXXFLAGS) -c $< -o $@
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With